Class: Grape::Validations::ContractScope

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

Defined Under Namespace

Classes: Validator

Instance Method Summary collapse

Constructor Details

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

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

Parameters:

  • api (API)

    the API endpoint to modify.

  • contract (defaults to: nil)

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

Yields:

  • a block yielding a new schema class. 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.namespace_stackable(:contract_key_map, key_map)

  validator_options = {
    validator_class: Validator,
    opts: { schema: contract, fail_fast: false }
  }

  api.namespace_stackable(:validations, validator_options)
end