J
John Platte
Trying to work some attr_accessor - style magic so I can refactor a
bunch of menial methods into a single declaration. Can't subclass, so
I'm trying to do it with a module.
In the code below, I expect both of the "puts" lines to work on the
"abc" string, but I can't figure out what I'm missing. Can anyone
enlighten me here?
module FooModule
def delegate(*methods)
methods.each {|method|
module_eval %{
def #{method}
@new_receiver.#{method}
end
}
}
end
module_function :delegate
end
class TryIt
include FooModule
FooModule.delegate :intern
delegate :capitalize
def initialize(obj)
@new_receiver = obj
end
end
t = TryIt.new("abc")
puts t.intern
puts t.capitalize
=====
$ ruby demo.rb
demo.rb:17: undefined method `delegate' for TryIt:Class (NoMethodError)
(now comment out the line "delegate :capitalize")
$ ruby demo.rb
abc
demo.rb:25: undefined method `capitalize' for #<TryIt:0x283c8
@new_receiver="abc"> (NoMethodError)
bunch of menial methods into a single declaration. Can't subclass, so
I'm trying to do it with a module.
In the code below, I expect both of the "puts" lines to work on the
"abc" string, but I can't figure out what I'm missing. Can anyone
enlighten me here?
module FooModule
def delegate(*methods)
methods.each {|method|
module_eval %{
def #{method}
@new_receiver.#{method}
end
}
}
end
module_function :delegate
end
class TryIt
include FooModule
FooModule.delegate :intern
delegate :capitalize
def initialize(obj)
@new_receiver = obj
end
end
t = TryIt.new("abc")
puts t.intern
puts t.capitalize
=====
$ ruby demo.rb
demo.rb:17: undefined method `delegate' for TryIt:Class (NoMethodError)
(now comment out the line "delegate :capitalize")
$ ruby demo.rb
abc
demo.rb:25: undefined method `capitalize' for #<TryIt:0x283c8
@new_receiver="abc"> (NoMethodError)