Class: Validate::Arguments::ArgumentsGuard

Inherits:
Object
  • Object
show all
Defined in:
lib/validate/arguments.rb

Constant Summary collapse

DEFAULT_VALUE =
BasicObject.new

Instance Method Summary collapse

Constructor Details

#initialize(method, rules) ⇒ ArgumentsGuard

Returns a new instance of ArgumentsGuard.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/validate/arguments.rb', line 54

def initialize(method, rules)
  signature = []
  assertions = []

  method.parameters.each do |(kind, name)|
    case kind
    when :req
      signature << name.to_s
    when :opt
      signature << "#{name} = DEFAULT_VALUE"
    when :rest
      signature << "*#{name}"
    when :keyreq
      signature << "#{name}:"
    when :key
      signature << "#{name}: DEFAULT_VALUE"
    when :keyrest
      signature << "**#{name}"
    when :block
      signature << "&#{name}"
    else
      raise Error::ArgumentError,
            "unsupported parameter type #{kind}"
    end
    next unless rules.include?(name)

    assertions <<
      "@rules[:#{name}].assert(#{name}, message: '#{name}') unless #{name}.eql?(DEFAULT_VALUE)"
  end

  singleton_class.class_eval(<<~RUBY, __FILE__, __LINE__)
    def enforce!(#{signature.join(', ')})
      #{assertions.join("\n  ")}
    end
  RUBY

  @rules = rules
end