在method_missing中查找实例

时间:2013-01-17 15:01:34

标签: ruby metaprogramming

我有一种情况,我希望能够打电话

foo.bar.baz arg1,arg2...argn

有时baz不会被定义,我将使用method_missing捕获但是从'bar'返回的对象的method_missing我希望能够得到'foo'。那就是我想得到foo所指的对象的引用

我可以假设的一个解决方案是,是否可以获取调用上下文/父上下文的绑定对象。也就是说,从method_missing里面获取绑定对象,因为它正在调用foo.bar

所以我的问题是,在method_missing中是否有任何方法,我可以回溯(在这种情况下为foo)?如果我必须设置好的呼叫,只要它在解释时完成,而不是使用#extend或其它会严重影响缓存/影响性能的话。

2 个答案:

答案 0 :(得分:0)

def method_missing *_; self end

答案 1 :(得分:0)

class MyFooClass
    attr_reader :value

    def initialize(value)
        @value = value
    end

        # In order to say foo.bar, the class of foo must define bar.
    def bar
        puts "bar sent to #{self}"
            # return a class where method_missing is defined,
            # and pass it a reference to foo
        MyBarClass.new(self)
    end
end # MyFooClass

class MyBarClass
    def initialize(foo)
        @foo = foo
    end

    def method_missing(name, *args, &block)
        puts "missing #{name} in #{self.class}"
        self.class.class_eval %Q{
            puts "about to define #{name}"
            def #{name}(*args)
                puts "in #{name} on self=#{self} with args=#{args}"
                puts "foo is #{@foo} and it's value is <#{@foo.value}>"
            end
        }
        puts "after define, execute #{name}"
        self.send(name, *args)
    end
end # MyBarClass

foo = MyFooClass.new('value of foo') # result of an expression
foo.bar.baz 'arg1' # define baz for future reference and execute it
print 'MyBarClass.instance_methods : '; p MyBarClass.instance_methods(false)

执行:

$ ruby -w t.rb
bar sent to #<MyFooClass:0x10195c750>
missing baz in MyBarClass
about to define baz
after define, execute baz
in baz on self=#<MyBarClass:0x10195c6b0> with args=arg1
foo is #<MyFooClass:0x10195c750> and it's value is <value of foo>
MyBarClass.instance_methods : ["baz", "method_missing"]