从类方法proc中访问实例方法

时间:2013-11-23 09:31:55

标签: ruby

我正在尝试在类上调用proc但是使用继承的类从中访问实例方法。我认为一些模拟代码会更有意义:)

class Bar
  def self.foo &block
    @foo ||= block
  end
  def foo; self.class.foo.call(); end
  def bar; 'bar'; end
end

class Foo < Bar
  foo do
    bar
  end
end

Foo.new.foo
# NameError: undefined local variable or method `bar' for Foo:Class

我希望能够访问Bar类上的bar实例方法。使用继承类中的块调用foo类方法的原因是DSL要求的一部分,但是对于更好设计的任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

块具有词法范围,包括self的值。在定义块的位置,selfBarBar不响应bar。您需要在对象的上下文中评估块(在本例中是{em>实例的Bar而不是Bar本身),您要调用它们的方法。这就是instance_eval的作用:

class Bar
  def self.foo(&block) @foo ||= block end
  def foo; instance_eval(&self.class.foo) end
  def bar; 'bar' end
end

class Foo < Bar; foo do bar end end

Foo.new.foo
# => 'bar'

请注意,关于instance_eval的所有常规免责声明都适用:因为您更改了self方法和实例变量的值,块作者可能不会使用这些变量。