Skip to content

Instantly share code, notes, and snippets.

@danreedy
Last active August 29, 2015 14:13
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 danreedy/da3a6d42367c955ce093 to your computer and use it in GitHub Desktop.
Save danreedy/da3a6d42367c955ce093 to your computer and use it in GitHub Desktop.
The code and tests for the "Deep Fetch" by Dan Reedy
#!/usr/bin/env ruby
require 'minitest/autorun'
Hash.class_eval do
def deep_fetch(*keys, default: nil)
keys.reduce(self) do |memo, key|
memo.fetch(key)
end
rescue KeyError
default.nil? ? raise : default
end
def fetch_keypath(keypath, default: nil)
deep_fetch(*keypath.split('.'), default: default)
end
end
describe Hash do
before do
@hash = {
"webserver" => {
"users" => {
"admin" => {
"password" => "some amazing password"
}
}
}
}
end
describe '#deep_fetch' do
it 'returns the correct value for the provided keys' do
@hash.deep_fetch('webserver','users','admin','password').must_equal 'some amazing password'
end
it 'raises KeyError if the provided keys do not exist' do
-> { @hash.deep_fetch('webserver','users','jdoe','password') }.must_raise KeyError
end
it 'returns the provided default value if the key does not exist' do
@hash.deep_fetch('webserver','users','jdoe','password', default: 'Key Missing').must_equal 'Key Missing'
end
it 'returns the provided default value if the key does not exist' do
@hash.deep_fetch('webserver','users','jdoe','password', default: false).must_equal false
end
end
describe '#fetch_keypath' do
it 'returns the correct value for the provided keypath' do
@hash.fetch_keypath('webserver.users.admin.password').must_equal 'some amazing password'
end
it 'raises KeyError if the provided keys do not exist' do
-> { @hash.fetch_keypath('webserver.users.jdoe.password') }.must_raise KeyError
end
it 'returns the provided default value if the key does not exist' do
@hash.fetch_keypath('webserver.users.jdoe.password', default: 'Key Missing').must_equal 'Key Missing'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment