Created
November 30, 2012 18:27
-
-
Save xunker/4177581 to your computer and use it in GitHub Desktop.
The case for named arguments in Ruby
This file contains 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
# Usage: | |
# | |
# def foo(opts = {}) | |
# opts.require_keys!(:bar) | |
# puts 'yay' | |
# end | |
# | |
# foo() | |
# => MissingRequiredHashKeyError: Hash key ':bar' missing | |
# | |
# foo(:bar) | |
# => yay | |
class MissingRequiredHashKeyError < StandardError; end | |
class Hash | |
def require_keys!(*required_keys) | |
required_keys.flatten.each do |required_key| | |
if !self.keys.include?(required_key) | |
key_string = (required_key.is_a?(Symbol) ? ":#{required_key}" : required_key ) | |
raise MissingRequiredHashKeyError, "Hash key '#{key_string}' missing" | |
end | |
end | |
true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment