Skip to content

Instantly share code, notes, and snippets.

@kolo
Created April 7, 2011 13:07
Show Gist options
  • Save kolo/907749 to your computer and use it in GitHub Desktop.
Save kolo/907749 to your computer and use it in GitHub Desktop.
settings storage class
require 'yaml'
require 'test/unit'
TEST_CONFIG = <<END_OF_CONFIG
filename: settings.rb
development:
database: settings-development
port: 3366
test:
hostname: localhost
port: 8000
END_OF_CONFIG
class Settings
def initialize(raw_opts)
mod = Module.new
raw_opts.each { |key, value|
var = to_var(key)
if value.instance_of?(Hash)
instance_variable_set(var, Settings.new(value))
else
instance_variable_set(var, value)
end
mod.send(:define_method, key) {
return instance_variable_get(var)
}
}
self.extend(mod)
end
private
def to_var(key)
("@"+key.to_s).to_sym
end
end
class SettingsTest < Test::Unit::TestCase
def setup
@settings = Settings.new(YAML.load(TEST_CONFIG))
end
def test_all_values_loaded
assert_equal("settings.rb", @settings.filename)
assert_equal("settings-development", @settings.development.database)
assert_equal(3366, @settings.development.port)
assert_equal("localhost", @settings.test.hostname)
assert_equal(8000, @settings.test.port)
end
def test_to_var
assert_equal(@settings.send(:to_var, :key), :@key)
end
end
@kolo
Copy link
Author

kolo commented Apr 8, 2011

Thanks for advice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment