Skip to content

Instantly share code, notes, and snippets.

@aymerick
Created October 31, 2013 17:16
Show Gist options
  • Save aymerick/7253438 to your computer and use it in GitHub Desktop.
Save aymerick/7253438 to your computer and use it in GitHub Desktop.
class Prout
def initialize(delegate)
@delegate = delegate
end
def delegate
@delegate
end
def method_missing(sym, *args, &blk)
if self.delegate.respond_to?(sym)
puts "Creating method :#{sym} on delegate"
# define an instance method so that future calls on that method do not rely on method_missing
self.instance_eval <<-RUBY
def #{sym}(*args, &blk)
self.delegate.__send__(:#{sym}, *args, &blk)
end
RUBY
self.__send__(sym, *args, &blk)
else
super
end
end
def a(x)
puts "a: #{x}"
end
end
class Meuh
def b(x, y)
puts "b: #{x}, #{y}"
yield(x + y) if block_given?
end
end
meuh = Meuh.new
prout = Prout.new(meuh)
prout.a(1)
# => a: 1
prout.b(2, 3)
# => Creating method :b on delegate
# => b: 2, 3
prout.b(5, 6) do |sum|
puts "in block: #{sum}"
end
# b: 5, 6
# in block: 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment