Odkazy:
class Config
def initialize(data={})
@data = {}
update!(data)
end
def update!(data)
data.each do |key, value|
self[key] = value
end
end
def [](key)
@data[key.to_sym]
end
def []=(key,value)
if value.class == Hash
@data[key.to_sym] = Config.new(value)
else
@data[key.to_sym] = value
end
end
def method_missing(sym, *args)
if sym.to_s =~ /(.+)=$/
self[$1] = args.first
else
self[sym]
end
end
endPoužití:
config = Config.new
config.database = 'database_name'
config.username = 'user'
config.db_hosts = {
'sj' => 'sj.example.com',
'ny' => 'ny.example.com'
}
config.username # => 'user'
config.db_hosts.ny # => 'ny.example.com'Použití třídy Hash místo třídy OpenStruct má své výhody hierarchických konfigurací.
yaml_data = "
---
database: mydb
auth:
user: myuser
pass: mypass
"
require 'yaml'
config = Config.new(YAML.load(yaml_data))
config.auth.user # => "myuser"Použití Configatron
def configatron
@configatron ||= Configatron.new
endconfigatron do |config|
config.app_name = "My Awesome App"
config.database_url = "postgres://localhost/somedb"
# etc …
end