-
-
Save georgkreimer/1278152 to your computer and use it in GitHub Desktop.
MappedHash
This file contains 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 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 |
This file contains 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
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 |
This file contains 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 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