【发布时间】:2016-05-25 23:11:58
【问题描述】:
要覆盖子类中的类常量,可以这样做:
class Foo
CONST = [:foo, :baz]
def self.const
self::CONST
end
end
class Bar < Foo
CONST = [:foo, :bar]
end
print Foo.const # [:foo, :baz]
print Bar.const # [:foo, :bar]
这按预期工作。问题是当我尝试从类方法调用它时,例如在使用 define_method 时:
class Foo
CONST = [:foo, :baz]
def self.const
self::CONST
end
self.const.each do |c|
define_method("#{c}?") {
"#{c} exists"
}
end
end
foo = Foo.new
print foo.baz? # baz exists.
bar = Bar.new
print bar.bar? # undefined method `bar?'
如何重写类常量,以便在这种情况下定义正确的方法bar?,而不必复制子类中的代码?有没有一种 DRY 方式可以做到这一点,而不必使用类变量而不是类常量?
【问题讨论】:
-
不清楚您要做什么。不复制子类中的代码不就行了吗?
-
@sawa:是的,但它不起作用:)
-
怎么不工作了?
-
@sawa:
undefined method bar? -
你不想这样吗?
标签: ruby