Commit f8903920fb6c3239c6b73b1c1c7580c44631347c
1 parent
4884d455
Exists in
master
symbolize_keys method. fix for #33
Showing
2 changed files
with
34 additions
and
2 deletions
Show diff stats
lib/settingslogic.rb
... | ... | @@ -10,7 +10,7 @@ class Settingslogic < Hash |
10 | 10 | def name # :nodoc: |
11 | 11 | self.superclass != Hash && instance.key?("name") ? instance.name : super |
12 | 12 | end |
13 | - | |
13 | + | |
14 | 14 | # Enables Settings.get('nested.key.name') for dynamic access |
15 | 15 | def get(key) |
16 | 16 | parts = key.split('.') |
... | ... | @@ -167,7 +167,22 @@ class Settingslogic < Hash |
167 | 167 | end |
168 | 168 | EndEval |
169 | 169 | 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 | + | |
171 | 186 | def missing_key(msg) |
172 | 187 | return nil if self.class.suppress_errors |
173 | 188 | ... | ... |
spec/settingslogic_spec.rb
... | ... | @@ -152,6 +152,23 @@ describe "Settingslogic" do |
152 | 152 | it "should allow a name setting to be overriden" do |
153 | 153 | Settings.name.should == 'test' |
154 | 154 | 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 | |
155 | 172 | |
156 | 173 | # Put this test last or else call to .instance will load @instance, |
157 | 174 | # masking bugs. | ... | ... |