Created
March 28, 2014 03:19
-
-
Save chendo/9824605 to your computer and use it in GitHub Desktop.
My take on required keyword arguments in Ruby 2.0. This solution throws a nice backtrace, but still requires a name to be passed in.
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
module RequiredKeywordArguments | |
def required!(name) | |
backtrace = caller_locations(1).map { |c| c.to_s } | |
ex = ArgumentError.new("Missing required keyword argument '#{name}'") | |
ex.set_backtrace(backtrace) | |
raise ex | |
end | |
end | |
class Foo | |
include RequiredKeywordArguments | |
def bar(baz: required!(:baz)) | |
end | |
end | |
Foo.new.bar() | |
# https://eval.in/127896 | |
# /tmp/execpad-157492e20293/source-157492e20293:13:in `bar': Missing required keyword argument 'baz' (ArgumentError) | |
# from /tmp/execpad-157492e20293/source-157492e20293:18:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment