Skip to content

Instantly share code, notes, and snippets.

@mike-burns
Created May 24, 2011 00:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mike-burns/987910 to your computer and use it in GitHub Desktop.
Save mike-burns/987910 to your computer and use it in GitHub Desktop.
Implicts in Ruby, via Scala
# 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? && !@transformer.nil?
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