Skip to content

Instantly share code, notes, and snippets.

@heisters
Created April 24, 2009 20:37
Show Gist options
  • Save heisters/101336 to your computer and use it in GitHub Desktop.
Save heisters/101336 to your computer and use it in GitHub Desktop.
access elements deep in a nested enumerable safely
# Makes it easy to access elements deep within a nested Enumerable. Rather than
# having to do
#
# enum[:foo] && enum[:foo][:bar]
#
# you can just do
#
# enum.try_keys :foo, :bar
module Enumerable
def try_keys *keys
keys.inject(self) do |target, key|
(target.respond_to?(:[]) and target[key]) or break
end
end
end
describe "an enumerable with try_keys", :shared => true do
it "should return the value if it exists" do
@enumerable.try_keys(*@good_keys).should == @expected
end
it "should return nil if it doesn't exist" do
@enumerable.try_keys(*@bad_keys).should be_nil
end
end
describe "Enumerable#try_keys" do
describe "with a Hash" do
before :each do
@expected = true
@enumerable = {:foo => {:bar => @expected}}
@good_keys = [:foo, :bar]
@bad_keys = [:baz, :bar]
end
it_should_behave_like "an enumerable with try_keys"
end
describe "with an Array" do
before :each do
@expected = true
@enumerable = [:foo, [:bar, @expected]]
@good_keys = [1, 1]
@bad_keys = [0, 1]
end
it_should_behave_like "an enumerable with try_keys"
end
describe "with an Array of Hashes" do
before :each do
@expected = true
@enumerable = [:foo, {:bar => false, :baz => @expected}]
@good_keys = [1, :baz]
@bad_keys = [0, :baz]
end
it_should_behave_like "an enumerable with try_keys"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment