我正在尝试在类上调用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要求的一部分,但是对于更好设计的任何建议都将受到赞赏。
答案 0 :(得分:1)
块具有词法范围,包括self
的值。在定义块的位置,self
为Bar
而Bar
不响应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
方法和实例变量的值,块作者可能不会使用这些变量。