Created
October 31, 2014 12:53
-
-
Save gavinheavyside/09b0bea1f2de2e9b0496 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
class HashWithIndifferentAccess < Hash | |
def [](key) | |
super(convert_key(key)) | |
end | |
def []=(key, value) | |
super(convert_key(key), value) | |
end | |
def self.[] (*args) | |
mapped_args = args.each_with_index.map{ |arg, i| i.even? ? convert_key(arg) : arg } | |
super(*mapped_args) | |
end | |
def convert_key(key) | |
self.class.convert_key(key) | |
end | |
def self.convert_key(key) | |
key.to_sym | |
end | |
def store(key, value) | |
super(convert_key(key), value) | |
end | |
def fetch(key, *args) | |
super(convert_key(key), *args) | |
end | |
end | |
describe HashWithIndifferentAccess do | |
let(:h) { HashWithIndifferentAccess.new } | |
it 'can save string, read symbol' do | |
h['foo'] = 'bar' | |
expect(h[:foo]).to eq('bar') | |
end | |
it 'can save symbol, read string' do | |
h[:foo] = 'bar' | |
expect(h['foo']).to eq('bar') | |
end | |
it 'can be initialized with a list of k,v pairs' do | |
h2 = HashWithIndifferentAccess['foo', 'bar', :bar, 'baz'] | |
expect(h2[:foo]).to eq('bar') | |
expect(h2['bar']).to eq('baz') | |
end | |
it 'can store' do | |
h.store('foo', 'bar') | |
expect(h[:foo]).to eq('bar') | |
end | |
it 'can fetch' do | |
h[:foo] = 'bar' | |
expect(h.fetch('foo')).to eq('bar') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment