Skip to content

Instantly share code, notes, and snippets.

@chendo
Created March 28, 2014 03:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chendo/9824605 to your computer and use it in GitHub Desktop.
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.
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