Module: Stannum::ParameterValidation::ClassMethods

Defined in:
lib/stannum/parameter_validation.rb

Overview

Defines a DSL for validating method parameters.

Instance Method Summary collapse

Instance Method Details

#validate_parameters(method_name, &validations) ⇒ Object

Creates a validation contract and wraps the named method.

The provided block is used to create a ParametersContract, and supports the same DSL used to define one.



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/stannum/parameter_validation.rb', line 120

def validate_parameters(method_name, &validations)
  method_name = method_name.intern
  contract    = Stannum::Contracts::ParametersContract.new(&validations)

  self::MethodValidations.add_contract(method_name, contract)

  self::MethodValidations.define_method(method_name) \
  do |*arguments, **keywords, &block|
    result = match_parameters_to_contract(
      arguments:   arguments,
      block:       block,
      contract:    contract,
      keywords:    keywords,
      method_name: method_name
    )

    return result unless result == VALIDATION_SUCCESS

    if keywords.empty?
      super(*arguments, &block)
    else
      super(*arguments, **keywords, &block)
    end
  end
end