【发布时间】:2014-03-25 17:50:44
【问题描述】:
这是我设法做到这一点的一种方法。
class Test
class << self
attr_accessor :stuff
def thing msg
@stuff ||= ""
@stuff += msg
end
end
def initialize
@stuff = self.class.stuff
puts @stuff
end
end
# Is there a better way of accomplishing this?
class AThing < Test
thing "hello"
thing "world"
end
AThing.new
# Prints "helloworld"
AThing 中的界面是我想要的最终结果。我真正讨厌(而且我觉得必须有更好的方法)是@stuff = self.class.stuff。
有没有更好的方法来使用 eigenclass 为自身的所有实例设置默认数据集,同时保持“漂亮”的界面?
我想用这样的代码完成的是有一个类方法,比如 add_something ,它将一些东西添加到存储在类变量中的数组中。
当类被实例化时,它将在其初始化方法中使用这个数组来设置该实例的状态。
【问题讨论】:
-
@stuff = self.class.stuff有什么不好?类变量会起作用吗? -
@stuff = @@stuff?我只是觉得它很笨拙。虽然它会对普通用户隐藏。我也希望它不要成为公共界面的一部分
-
是的。这就是我的意思。然后,您不需要在 eigenclass 中执行此操作。
-
这很有意义。我一定是真的累了。一如既往地感谢。你能发布一个我可以标记的答案吗?
标签: ruby metaprogramming instantiation eigenclass