I have some configuration options for a program stored in a JSON file. I want to be able to access the options in several different classes without explicitly having to open the file and read the configuration in each class. Is there a good, DRY way to do this?
I tried creating a module which reads the configuration into a class variable, and just include the module in every class, but is this a good use of class variables? Reading this makes me wary of class variables.
Here is what I have right now:
module Config
@@config = nil
def self.included(base)
if @@config.nil?
open('config.json', 'r') { |f| @@config = JSON.load(f) }
end
end
end
Thanks!
Update:
Maybe it’s better just to place all the classes that require the configuration under it’s own namespace?
module MyFishTank
Config = { "location" => "My room" }
Class Fish
def location
Config['location']
end
end
end
fish = MyFishTank::Fish.new
puts fish.location #=> "My room"
Why not something like this:
Edit: if you want to avoid class method invocation (which seems wrong to me, as the configuration is indeed class-wide, not instance-wide), you can do something like:
Though there probably is more succinct way of doing it.