Created
April 7, 2011 13:07
-
-
Save kolo/907749 to your computer and use it in GitHub Desktop.
settings storage class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice solution, you can also take a look at Configatron https://github.com/markbates/configatron