Created
May 24, 2011 00:05
-
-
Save mike-burns/987910 to your computer and use it in GitHub Desktop.
Implicts in Ruby, via Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Implicits in Ruby, based on Scala. Works like: | |
# | |
# implicitly.from(BaseClass).to(WrapperClass).via do |base_object| | |
# WrapperClass.new(base_object) | |
# end | |
# | |
def implicitly | |
Implicit.new | |
end | |
class Implicit | |
def from(starting_class) | |
@starting_class = starting_class | |
try_to_do_everything | |
self | |
end | |
def to(ending_class) | |
@ending_class = ending_class | |
try_to_do_everything | |
self | |
end | |
def via(&transformer) | |
@transformer = transformer | |
try_to_do_everything | |
self | |
end | |
def try_to_do_everything | |
if !@starting_class.nil? && !@ending_class.nil? && [email protected]? | |
transformer = @transformer | |
(@ending_class.instance_methods-Object.instance_methods).each do |meth_name| | |
@starting_class.class_eval do | |
define_method(meth_name) do |*args| | |
transformer.call(self).send(meth_name,*args) | |
end | |
end | |
end | |
end | |
end | |
private :try_to_do_everything | |
end | |
# For example ... | |
class FixnumWithTime | |
def initialize(n) | |
@n = n | |
end | |
def minutes | |
seconds * 60 | |
end | |
def hours | |
minutes * 60 | |
end | |
def seconds | |
@n | |
end | |
end | |
implicitly.from(Fixnum).to(FixnumWithTime).via {|n| FixnumWithTime.new(n) } | |
p 2.minutes | |
p 2.hours |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment