[英]Setting instance defaults in the eigenclass of ruby classes
This is one way I've managed to accomplish this. 这是我设法做到这一点的一种方法。
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"
The interface in AThing is what I would like as a final result. 我希望最终结果是AThing中的界面。 What I really hate (and I feel there must be a better way of accomplishing) is @stuff = self.class.stuff. 我真正讨厌的是(我觉得必须有一种更好的完成方式)是@stuff = self.class.stuff。
Is there a better way to use the eigenclass to set the default dataset for all instances of itself while maintaining a "pretty" interface? 有没有一种更好的方法可以使用eigenclass为其自身的所有实例设置默认数据集,同时保持“漂亮”接口?
What I want to accomplish with code like this is to have a class method, say add_something that adds something to an array stored in a class variable. 我想要用这样的代码完成的事情是拥有一个类方法,例如add_something,它可以将一些东西添加到存储在类变量中的数组中。
When the class is instantiated, it will use this array in its' initialize method to setup the state of that instance. 当实例化该类时,它将在其initialize方法中使用此数组来设置该实例的状态。
class Test
@@stuff = ""
class << self
def thing msg
@@stuff.concat(msg)
end
end
def initialize
puts @@stuff
end
end
class AThing < Test
thing "hello"
thing "world"
end
AThing.new
# Prints "helloworld"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.