Class: Grape::Validations::Types::DryTypeCoercer

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

Overview

A base class for classes which must identify a coercer to be used. If the +strict+ argument is true, it won't coerce the given value but check its type. More information there https://dry-rb.org/gems/dry-types/1.2/built-in-types/

Direct Known Subclasses

ArrayCoercer, PrimitiveCoercer

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, strict = false) ⇒ DryTypeCoercer

Returns a new instance of DryTypeCoercer.



48
49
50
51
52
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 48

def initialize(type, strict = false)
  @type = type
  @strict = strict
  @scope = strict ? DryTypes::Strict : DryTypes::Params
end

Class Method Details

.coercer_instance_for(type, strict = false) ⇒ Object

Returns an instance of a coercer for a given type



33
34
35
36
37
38
39
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 33

def coercer_instance_for(type, strict = false)
  return PrimitiveCoercer.new(type, strict) if type.instance_of?(Class)

  # in case of a collection (Array[Integer]) the type is an instance of a collection,
  # so we need to figure out the actual type
  collection_coercer_for(type.class).new(type, strict)
end

.collection_coercer_for(type) ⇒ Object

Returns a collection coercer which corresponds to a given type. Example:

collection_coercer_for(Array) #=> Grape::Validations::Types::ArrayCoercer



26
27
28
29
30
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 26

def collection_coercer_for(type)
  collection_coercers.fetch(type) do
    DryTypeCoercer.collection_coercers[type] = Grape::Validations::Types.const_get("#{type.name.camelize}Coercer")
  end
end

Instance Method Details

#call(val) ⇒ Object

Coerces the given value to a type which was specified during initialization as a type argument.

Parameters:

  • val (Object)


58
59
60
61
62
63
64
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 58

def call(val)
  return if val.nil?

  @coercer[val]
rescue Dry::Types::CoercionError => _e
  InvalidValue.new
end