I need to access the config variables from inside another class of a module.
In test.rb, how can I get the config values from client.rb? @config gives me an uninitialized var. It’s in the same module but a different class.
Is the best bet to create a new instance of config? If so how do I get the argument passed in through run.rb?
Or, am I just structuring this all wrong or should I be using 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
@config is a instance variable, if you want get it from outside you need to provide accessor, and give to Easy class self object.
client.rb:
test.rb
If you use @@config, then you can acces to this variable without giving a self object, with class_variable_get.
I recommend to you read metaprogramming ruby book.