Skip to content

Instantly share code, notes, and snippets.

@georgkreimer
Forked from jeffkreeftmeijer/mapped_hash.rb
Created October 11, 2011 14:02
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 georgkreimer/1278152 to your computer and use it in GitHub Desktop.
Save georgkreimer/1278152 to your computer and use it in GitHub Desktop.
MappedHash
class MappedHash < Hash
attr_writer :mappings
def mappings
@mappings || {}
end
def [](name)
super || super(mappings[name])
end
def self.from_hash(hash)
new.tap do |mapped_hash|
hash.each { |key, value| mapped_hash[key] = value }
end
end
end
require File.expand_path('mapped_hash')
describe MappedHash do
shared_examples_for "an existing hash key" do
it { should be_nil }
context "when the 'foo' attribute is set to 'baz'" do
before { mapped_hash[:foo] = 'baz' }
it { should == 'baz' }
end
end
let(:mapped_hash) { MappedHash.new }
describe "#mappings" do
subject { mapped_hash.mappings }
it { should == {} }
context "after adding `:name => 'Naam'` as a mapping" do
before { mapped_hash.mappings = {:name => 'Naam'} }
it { should == {:name => 'Naam'} }
end
end
describe "#[:foo]" do
subject { mapped_hash[:foo] }
it_should_behave_like 'an existing hash key'
end
describe "#[:bar] (mapped to foo)" do
before { mapped_hash.mappings = {:bar => :foo} }
subject { mapped_hash[:bar] }
it_should_behave_like 'an existing hash key'
end
describe ".from_hash" do
context "when passing an empty hash" do
subject { MappedHash.from_hash({}) }
it { should be_empty }
end
context "when passing a hash with a value" do
let(:mapped_hash) { MappedHash.from_hash({:foo => 'bar'}) }
subject { mapped_hash }
it { should have_key :foo }
describe "the value of :foo" do
subject { mapped_hash[:foo] }
it { should == 'bar' }
end
end
end
end
class UglyDutchHash < MappedHash
def mappings
{
:name => 'Naam'
}
end
end
# h = UglyDutchHash.from_hash({'Naam' => 'Barrie'})
# => {"Naam"=>"Barrie"}
# h[:name]
# => "Barrie"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment