Created
May 2, 2014 15:45
-
-
Save JoshCheek/6268d6a615c2fad8781e to your computer and use it in GitHub Desktop.
Are mandatory keyword args a thing? I find myself wanting to do this a lot. UPDATE: answer is yes, see https://gist.github.com/JacobNinja/a38d0f4b02759c910dc3
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
def mandatory | |
required = method(caller.first[/(?<=`).*(?=')/] # => "crazy_arglist!" | |
) # => #<Method: Object#crazy_arglist!> | |
.parameters # => [[:req, :a], [:opt, :b], [:rest, :c], [:key, :d], [:key, :e], [:keyrest, :f], [:block, :g]] | |
.select { |type, name| type == :key } # => [[:key, :d], [:key, :e]] | |
.map { |type, name| name } # => [:d, :e] | |
raise ArgumentError, "Must provide #{required.join ", "}" # ~> ArgumentError: Must provide d, e | |
end | |
def crazy_arglist!(a, b=1, *c, d: mandatory, e: mandatory, **f, &g) | |
"line #{caller.first.split(":")[1]}" # => "line 16" | |
end | |
# works when you provide the mandatory args | |
crazy_arglist! nil, d: nil, e: nil # => "line 16" | |
# blows up when you don't, but is kind enough to tell you what you omitted, at least | |
crazy_arglist! nil | |
# ~> ArgumentError | |
# ~> Must provide d, e | |
# ~> | |
# ~> /var/folders/7g/mbft22555w3_2nqs_h1kbglw0000gn/T/seeing_is_believing_temp_dir20140502-17238-1bfctnw/program.rb:7:in `mandatory' | |
# ~> /var/folders/7g/mbft22555w3_2nqs_h1kbglw0000gn/T/seeing_is_believing_temp_dir20140502-17238-1bfctnw/program.rb:10:in `crazy_arglist!' | |
# ~> /var/folders/7g/mbft22555w3_2nqs_h1kbglw0000gn/T/seeing_is_believing_temp_dir20140502-17238-1bfctnw/program.rb:19:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment