Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.