-1

我有一种情况,我想打电话

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

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

我可以假设的一种解决方案是是否有可能获取调用上下文/父上下文的绑定对象。即从 method_missing 内部获取绑定对象,因为它在调用点foo.bar

所以我的问题是,在method_missing中有什么方法可以让我回溯(在这种情况下是foo)?如果我必须对调用进行检测,只要它在解释时完成并且不使用 #extend 或其他会严重破坏缓存/影响性能的东西,就可以了。

4

2 回答 2

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"]
于 2013-01-17T21:47:32.943 回答
0
def method_missing *_; self end
于 2013-01-17T15:11:48.587 回答