Created
May 9, 2012 14:45
-
-
Save jlogsdon/2645019 to your computer and use it in GitHub Desktop.
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
| c = Configuration.new | |
| c[:foo][:bar][:baz] = [1,2,3] | |
| c['foo']['bar']['baz'] # => [1,2,3] | |
| c[:foo] = {bar: :baz} | |
| c[:foo][:another][:brick][:in][:the] = :wall | |
| c # => {:foo => {:bar => :baz, :another => {:brick => {:in => {:the => :wall}}}}} | |
| class Configuration < ::Hash | |
| def initialize(hash={}) | |
| configure_from_hash(hash) | |
| end | |
| def configure_from_hash(hash) | |
| hash.each do |key, value| | |
| if value.is_a?(Hash) | |
| self[key] = Configuration.new(value) | |
| else | |
| self[key] = value | |
| end | |
| end | |
| end | |
| def [](key) | |
| super(key.to_sym) | |
| end | |
| def []=(key, value) | |
| if value.is_a?(Hash) && !value.is_a?(self.class) | |
| self[key].configure_from_hash(value) | |
| else | |
| super(key.to_sym, value) | |
| end | |
| end | |
| def default(key) | |
| self[key] = Configuration.new | |
| end | |
| def default=(*args) | |
| raise RuntimeError, "#{self.class} does not allow changing the default hash value" | |
| end | |
| end |
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
| describe Configuration do | |
| it { should be_a(Hash) } | |
| describe '#[]' do | |
| it 'creates keys on the fly' do | |
| subject[:foo] | |
| subject.should have_key(:foo) | |
| end | |
| it 'uses our Configuration class when creating keys' do | |
| subject[:foo].should be_a(described_class) | |
| end | |
| it 'normalizes keys to symbols' do | |
| subject['foo'] | |
| subject.should have_key(:foo) | |
| subject.should_not have_key('foo') | |
| end | |
| end | |
| describe '#[]=' do | |
| it 'normalizes keys to symbols' do | |
| subject['foo'] = :bar | |
| subject.should have_key(:foo) | |
| subject.should_not have_key('foo') | |
| end | |
| context 'when a hash is passed as the value' do | |
| it 'should be converted to a Configuration hash' do | |
| subject[:foo] = {bar: :baz} | |
| subject[:foo].should be_a(described_class) | |
| end | |
| end | |
| end | |
| describe '#default=' do | |
| it 'raises an error' do | |
| expect { subject.default = proc { } }.to raise_error | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment