Here's some test code that explains the issue I'm having. The Child class calls methods on the Parent class. One of the Parent's methods defines a new method called foo
on the Parent. After foo
is defined, attempting to call it from Child class works, but the context is completely different (I can only access Child's instance variables, not Parent's).
My guess here that this has something to do with Ruby's closures. Should I use something besides a block when I call Edit: I tried using a lambda and a proc, but it changed nothing.define_method
?
class Parent
@foo = 'foo'
def self.existing_method
puts "Calling existing_method, @foo is #{@foo}"
end
def self.define_new_method
self.class.send :define_method, :foo do
context = methods.include?('bar') ? 'child' : 'parent'
puts "Context is #{context}, @foo is #{@foo.inspect}"
end
end
end
class Child
@foo = 'childfoo'
def self.method_missing(*args, &block)
Parent.send args.shift, *args, &block
end
def self.bar
end
end
Child.existing_method # Calling existing_method, @foo is foo
Child.define_new_method
Child.foo # Context is child, @foo is "childfoo"
# (in Ruby 1.9, the context is parent, but
# @foo is still "childfoo")
Parent.foo # Context is parent, @foo is "foo"
This result is not what I want. Child.foo
's response should be the same as Parent.foo
's.
Thanks in advance!