Skip to content

Instantly share code, notes, and snippets.

@sumanmukherjee03
Created May 21, 2013 19:50
Show Gist options
  • Save sumanmukherjee03/5622676 to your computer and use it in GitHub Desktop.
Save sumanmukherjee03/5622676 to your computer and use it in GitHub Desktop.
Hash decoration with custom method for finding value for any nested key
require 'rspec'
RSpec.configure do |config|
config.mock_with :rspec
config.color_enabled = true
end
module MyHashTools
def get_val_for(sym)
if self[sym]
final = self[sym]
else
self.each do |(k, v)|
if v.class == Hash && !v.respond_to?(:get_val_for)
v.extend(MyHashTools)
final = v.get_val_for(sym)
end
end
end
final
end
end
describe Hash do
subject do
{:a => 3, :b => {:c => 5, :d => {:e => 7}}}
end
context "when my hash responds to get_val_for" do
before do
subject.extend(MyHashTools)
end
it "returns the value for the key" do
subject.get_val_for(:e).should eq(7)
end
end
context "when my hash does not respond to get_val_for" do
it "raises an error" do
expect { subject.get_val_for(:e) }.to raise_exception(NoMethodError)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment