bhbrinckerhoff
11/7/2004 8:12:00 AM
I've been trying to write a method that can dynamically mixin a module
to a class. I tried the following code:
#=========================================
module MixinUtils
def MixinUtils.includeMixin(className,mixinName,vars)
evalStr= <<-END
class #{className.to_s}
include #{mixinName.to_s}
end
END
eval(evalStr, vars)
end
end
module Foo
def printFoo
puts "foo"
end
end
class Array
def someMethod
self.each do |item|
MixinUtils.includeMixin(item.class.to_s,"Foo",binding)
item.printFoo
end
end
end
[1,2,3].someMethod
#======================================
But running this gives
question.rb:22:in `something': undefined method `printFoo' for
1:Fixnum (NoMethodError)
from question.rb:20:in `each'
from question.rb:20:in `something'
from question.rb:31
But if I take out the '[1,nil,true].something' and append
a=1
MixinUtils.includeMixin("Fixnum","Foo",binding)
a.printFoo
it produces
foo
as expected. Why the difference? Why does calling 'binding' inside a
block produce different results? Thanks in advance...
Ben