config hash to dot methods

This commit is contained in:
John Bender 2010-01-21 21:54:23 -08:00
parent 531aa5474d
commit 07be6f1ac0
5 changed files with 45 additions and 8 deletions

5
lib/hobo.rb Normal file
View File

@ -0,0 +1,5 @@
libdir = File.dirname(__FILE__)
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
require 'ostruct'
require 'hobo/config'

27
lib/hobo/config.rb Normal file
View File

@ -0,0 +1,27 @@
module Hobo
class Config
@@config = nil
class << self
def config
@@config
end
def parse!(source)
@@config ||= parse_to_struct(source)
end
private
def parse_to_struct(value)
return value unless value.instance_of?(Hash)
result = value.inject({}) do |acc, pair|
acc[pair.first] = parse_to_struct(pair.last)
acc
end
OpenStruct.new(result)
end
end
end
end

11
test/config_test.rb Normal file
View File

@ -0,0 +1,11 @@
require File.join(File.dirname(__FILE__), 'test_helper')
class ConfigTest < Test::Unit::TestCase
context "Hobo configuration" do
test "a hash source is converted to dot methods" do
Hobo::Config.parse!(:a => {:b => 1})
assert Hobo::Config.config.a.b == 1
end
end
end

View File

@ -18,4 +18,5 @@ begin
require 'ruby-debug'
rescue LoadError; end
require 'contest'
require File.join(File.dirname(__FILE__), '..', 'lib', 'hobo')
require 'contest'

View File

@ -1,7 +0,0 @@
require File.join(File.dirname(__FILE__), '..', 'test_helper')
class ConfigTest < Test::Unit::TestCase
test "assert" do
assert true
end
end