From 07be6f1ac0b19d2129fc822c0ebcf58603fda696 Mon Sep 17 00:00:00 2001 From: John Bender Date: Thu, 21 Jan 2010 21:54:23 -0800 Subject: [PATCH] config hash to dot methods --- lib/hobo.rb | 5 +++++ lib/hobo/config.rb | 27 +++++++++++++++++++++++++++ test/config_test.rb | 11 +++++++++++ test/test_helper.rb | 3 ++- test/unit/config_test.rb | 7 ------- 5 files changed, 45 insertions(+), 8 deletions(-) create mode 100644 lib/hobo.rb create mode 100644 lib/hobo/config.rb create mode 100644 test/config_test.rb delete mode 100644 test/unit/config_test.rb diff --git a/lib/hobo.rb b/lib/hobo.rb new file mode 100644 index 000000000..d4767f0a6 --- /dev/null +++ b/lib/hobo.rb @@ -0,0 +1,5 @@ +libdir = File.dirname(__FILE__) +$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir) + +require 'ostruct' +require 'hobo/config' diff --git a/lib/hobo/config.rb b/lib/hobo/config.rb new file mode 100644 index 000000000..99e9a594e --- /dev/null +++ b/lib/hobo/config.rb @@ -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 diff --git a/test/config_test.rb b/test/config_test.rb new file mode 100644 index 000000000..6b7b1d9ec --- /dev/null +++ b/test/config_test.rb @@ -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 diff --git a/test/test_helper.rb b/test/test_helper.rb index affa42529..a4d9c6972 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -18,4 +18,5 @@ begin require 'ruby-debug' rescue LoadError; end -require 'contest' \ No newline at end of file +require File.join(File.dirname(__FILE__), '..', 'lib', 'hobo') +require 'contest' diff --git a/test/unit/config_test.rb b/test/unit/config_test.rb deleted file mode 100644 index 01a7af4f5..000000000 --- a/test/unit/config_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require File.join(File.dirname(__FILE__), '..', 'test_helper') - -class ConfigTest < Test::Unit::TestCase - test "assert" do - assert true - end -end