Skip to content

Instantly share code, notes, and snippets.

@gavinheavyside
Created October 31, 2014 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinheavyside/09b0bea1f2de2e9b0496 to your computer and use it in GitHub Desktop.
Save gavinheavyside/09b0bea1f2de2e9b0496 to your computer and use it in GitHub Desktop.
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