我需要從另一個模塊類中訪問配置變量。如何通過同一模塊的類訪問類實例變量?
在test.rb中,如何從client.rb獲取配置值? @config
給了我一個未初始化的變種。它在相同的模塊中,但是是不同的類。
創建配置的新實例是最好的選擇嗎?如果是這樣,我怎麼得到通過run.rb傳入的參數?
或者,我只是構造這一切都錯了或應該使用attr_accessor
?
client.rb
module Cli
class Client
def initialize(config_file)
@config_file = config_file
@debug = false
end
def config
@config ||= Config.new(@config_file)
end
def startitup
Cli::Easy.test
end
end
end
config.rb
module Cli
class Config
def initialize(config_path)
@config_path = config_path
@config = {}
load
end
def load
begin
@config = YAML.load_file(@config_path)
rescue
nil
end
end
end
end
test.rb
module Cli
class Easy
def self.test
puts @config
end
end
end
run.rb
client = Cli::Client.new("path/to/my/config.yaml")
client.startitup
如果要從類外部訪問實例屬性,則需要提供一個訪問器。 – 2011-12-15 23:02:02