Last active
August 29, 2015 14:13
-
-
Save danreedy/da3a6d42367c955ce093 to your computer and use it in GitHub Desktop.
The code and tests for the "Deep Fetch" by Dan Reedy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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