Class: Grape::Validations::ContractScope

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/validations/contract_scope.rb

Instance Method Summary collapse

Constructor Details

#initialize(api, contract = nil) { ... } ⇒ ContractScope

Declare the contract to be used for the endpoint’s parameters.

Yields:

  • a block yielding a new schema class. Optional.

Parameters:

  • the API endpoint to modify.

  • (defaults to: nil)

    the contract or schema to be used for validation. Optional.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/grape/validations/contract_scope.rb', line 10

def initialize(api, contract = nil, &block)
  # When block is passed, the first arg is either schema or nil.
  contract = Dry::Schema.Params(parent: contract, &block) if block

  if contract.respond_to?(:schema)
    # It's a Dry::Validation::Contract, then.
    contract = contract.new
    key_map = contract.schema.key_map
  else
    # Dry::Schema::Processor, hopefully.
    key_map = contract.key_map
  end

  api.inheritable_setting.namespace_stackable[:contract_key_map] = key_map

  validator_options = {
    validator_class: Grape::Validations.require_validator(:contract_scope),
    opts: { schema: contract, fail_fast: false }
  }

  api.inheritable_setting.namespace_stackable[:validations] = validator_options
end