Class: Grape::Validations::Types::PrimitiveCoercer

Inherits:
DryTypeCoercer show all
Defined in:
lib/grape/validations/types/primitive_coercer.rb

Overview

Coerces the given value to a type defined via a +type+ argument during initialization. When +strict+ is true, it doesn't coerce a value but check that it has the proper type.

Constant Summary collapse

MAPPING =
{
  Grape::API::Boolean => DryTypes::Params::Bool,
  BigDecimal => DryTypes::Params::Decimal,
  Numeric => DryTypes::Params::Integer | DryTypes::Params::Float | DryTypes::Params::Decimal,
  TrueClass => DryTypes::Params::Bool.constrained(eql: true),
  FalseClass => DryTypes::Params::Bool.constrained(eql: false),

  # unfortunately, a +Params+ scope doesn't contain String
  String => DryTypes::Coercible::String
}.freeze
STRICT_MAPPING =
{
  Grape::API::Boolean => DryTypes::Strict::Bool,
  BigDecimal => DryTypes::Strict::Decimal,
  Numeric => DryTypes::Strict::Integer | DryTypes::Strict::Float | DryTypes::Strict::Decimal,
  TrueClass => DryTypes::Strict::Bool.constrained(eql: true),
  FalseClass => DryTypes::Strict::Bool.constrained(eql: false)
}.freeze

Instance Method Summary collapse

Methods inherited from DryTypeCoercer

coercer_instance_for, collection_coercer_for

Constructor Details

#initialize(type, strict = false) ⇒ PrimitiveCoercer

Returns a new instance of PrimitiveCoercer.



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/grape/validations/types/primitive_coercer.rb', line 29

def initialize(type, strict = false)
  super

  @type = type

  @coercer = (strict ? STRICT_MAPPING : MAPPING).fetch(type) do
    scope.const_get(type.name, false)
  rescue NameError
    raise ArgumentError, "type #{type} should support coercion via `[]`" unless type.respond_to?(:[])

    type
  end
end

Instance Method Details

#call(val) ⇒ Object



43
44
45
46
47
48
# File 'lib/grape/validations/types/primitive_coercer.rb', line 43

def call(val)
  return InvalidValue.new if reject?(val)
  return nil if val.nil? || treat_as_nil?(val)

  super
end