我有一个类:
class Configuration
def self.files
@@files ||= Array.new
end
end
Run Code Online (Sandbox Code Playgroud)
而不是这样做:
irb(main):001:0> Configuration.files
=> [file, file, file]
Run Code Online (Sandbox Code Playgroud)
我希望能够做到这一点:
irb(main):001:0> Configuration
=> [file, file, file]
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何,任何想法?
我正在考虑为'配置'常量添加额外的方法,这是一个哈希.所以如果我有......
Configuration = Hash.new
Configuration[:foo] = 'bar'
Run Code Online (Sandbox Code Playgroud)
我希望能够保存此配置哈希常量,以便能够转储到我希望能够使用的YAML文件并加载...
Configuration.load
Configuration.save
Run Code Online (Sandbox Code Playgroud)
我希望Configuration类看起来像
class Configuration
def self.save
open('config.yml', 'w') {|f| YAML.dump( self , f)}
end
def self.load
open('config.yml') {|f| YAML.load(f)}
end
end
Run Code Online (Sandbox Code Playgroud)
您可以通过向顶级对象添加一个隐式调用Configuration.files的方法来获得您正在寻找的效果,但是您无法真正引用类来调用它上面的方法.您可以将方法别名更短,但您需要调用一些东西.