Created
August 14, 2022 11:22
-
-
Save floehopper/19e7071878c3d78d921287fae43674ef to your computer and use it in GitHub Desktop.
Validate parameters against method signature
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
def valid?(method, ...) | |
signature = method.inspect | |
pattern = %r{(?:\.|#)#{method.name}\(([^\)]*)\)} | |
params = signature.match(pattern)[1] | |
params_with_nil_default_values = params.gsub('...', 'nil') | |
klass = Class.new | |
klass.class_eval "def self.#{method.name}(#{params_with_nil_default_values})\nend\n" | |
klass.public_send(method.name, ...) | |
true | |
rescue ArgumentError => e | |
p e | |
false | |
end | |
def m1(a, b=2, c:, d: 4); end | |
p valid?(method(:m1), 1, c: 3) | |
# => true | |
p valid?(method(:m1), 1, 2, c: 3, d: 4) | |
# => true | |
p valid?(method(:m1), c: 3) | |
# => #<ArgumentError: wrong number of arguments (given 0, expected 1..2; required keyword: c)> | |
# => false | |
p valid?(method(:m1), 1, 2, 3) | |
# => #<ArgumentError: wrong number of arguments (given 3, expected 1..2; required keyword: c)> | |
# => false | |
def m2(*args); end | |
p valid?(method(:m2), a: 1) | |
# => true | |
p valid?(method(:m2), 1) | |
# => true | |
p valid?(method(:m2), 1, 2, 3, 4) | |
# => true | |
def m3(**kwargs); end | |
p valid?(method(:m3), a: 1) | |
# => true | |
p valid?(method(:m3), a: 1, b:2, c: 3, d: 4) | |
# => true | |
p valid?(method(:m3), 1) | |
# => #<ArgumentError: wrong number of arguments (given 1, expected 0)> | |
# => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment