Skip to content

Instantly share code, notes, and snippets.

@fsvehla
Created June 7, 2009 22:27
Show Gist options
  • Save fsvehla/125518 to your computer and use it in GitHub Desktop.
Save fsvehla/125518 to your computer and use it in GitHub Desktop.
class Hash
def lookup_path(query)
path = query.split('.')
path.inject(self) do |result, key|
result[key] or return nil # || won't work.
end
end
end
begin
require "spec"
rescue LoadError
require "rubygems"
require "spec"
end
describe Hash, "#lookup_path" do
before(:each) do
@hash = {"dev" => {"server" => {"name" => "thor"}}}
end
it "should dive deep into the hash" do
@hash.lookup_path("dev.server").should == {"name" => "thor"}
@hash.lookup_path("dev.server.name").should == "thor"
end
it "should not care if the keys are strings or symbols" do
{"dev" => "foo"}.lookup_path("dev").should == "foo"
end
it "should return nil for a unknown first level key" do
{"dev" => "foo"}.lookup_path("test").should be_nil
end
it "should return nil for a unknown second level key" do
{"dev" => "foo"}.lookup_path("test.foo").should be_nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment