Skip to content

Commit f890392

Browse files
author
Erik Gustavson
committed
symbolize_keys method. fix for #33
1 parent 4884d45 commit f890392

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

lib/settingslogic.rb

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class << self
1010
def name # :nodoc:
1111
self.superclass != Hash && instance.key?("name") ? instance.name : super
1212
end
13-
13+
1414
# Enables Settings.get('nested.key.name') for dynamic access
1515
def get(key)
1616
parts = key.split('.')
@@ -167,7 +167,22 @@ def #{key}
167167
end
168168
EndEval
169169
end
170-
170+
171+
def symbolize_keys
172+
173+
inject({}) do |memo, tuple|
174+
175+
k = (tuple.first.to_sym rescue tuple.first) || tuple.first
176+
177+
v = k.is_a?(Symbol) ? send(k) : tuple.last # make sure the value is accessed the same way Settings.foo.bar works
178+
179+
memo[k] = v && v.respond_to?(:symbolize_keys) ? v.symbolize_keys : v #recurse for nested hashes
180+
181+
memo
182+
end
183+
184+
end
185+
171186
def missing_key(msg)
172187
return nil if self.class.suppress_errors
173188

spec/settingslogic_spec.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,23 @@ class NoSource < Settingslogic; end
152152
it "should allow a name setting to be overriden" do
153153
Settings.name.should == 'test'
154154
end
155+
156+
it "should allow symbolize_keys" do
157+
Settings.reload!
158+
result = Settings.language.haskell.symbolize_keys
159+
result.class.should == Hash
160+
result.should == {:paradigm => "functional"}
161+
end
162+
163+
it "should allow symbolize_keys on nested hashes" do
164+
Settings.reload!
165+
result = Settings.language.symbolize_keys
166+
result.class.should == Hash
167+
result.should == {
168+
:haskell => {:paradigm => "functional"},
169+
:smalltalk => {:paradigm => "object oriented"}
170+
}
171+
end
155172

156173
# Put this test last or else call to .instance will load @instance,
157174
# masking bugs.

0 commit comments

Comments
 (0)