【发布时间】:2016-08-31 02:37:49
【问题描述】:
假设我想在 Ruby 中创建一个宏。
class Base
def self.option(name,val)
options[name] = val
end
def self.options
@options ||= {}
end
end
class Foo < Base
option :one, 1
option :two, 2
end
Foo.options #=> {:one => 1, :two => 2}
好的,很简单。
但是如果我想继承 Foo 呢?
class Bar < Foo
end
Bar.options #=> {}
这太糟糕了。
所以很明显问题是每个类的类实例变量是唯一的,即。 @options inside Bar 与 @options inside Foo 不同。
所以也许是一个类变量?我一直无法找出其中一个的有效用途,让我们试试吧。
# the rest of the code unchanged
class Base
def self.options
@@options ||= {}
end
end
Bar.options #=> {:one => 1, :two => 2}
嘿,成功了! ...不是吗?
class Baz < Foo
option :three, 3
end
Foo.options #=> {:one => 1, :two => 2, :three => 3}
Bar.options #=> {:one => 1, :two => 2, :three => 3}
Baz.options #=> {:one => 1, :two => 2, :three => 3}
X-|
好的,我一直在谷歌上搜索这个问题,但没有发现任何有用的信息。我尝试了一些尝试阅读超类选项(如果已定义)的变体,但无济于事。我想我不妨问问。
你们中有人知道怎么做吗?还是根本不可能……
【问题讨论】:
标签: ruby inheritance macros