【发布时间】:2013-11-23 20:06:55
【问题描述】:
我试图在一个类上调用一个 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 要求的一部分,但任何关于更好设计的建议都将不胜感激。
【问题讨论】:
-
这两个 foo 令人困惑。
-
为什么
new.bar或将bar做成类方法不好? -
@SergioTulentsev 哈哈!抱歉......我的设计代码不是很有创意:)
标签: ruby