Class: Grape::Validations::Types::CustomTypeCoercer

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

Overview

This class will detect type classes that implement a class-level parse method. The method should accept one String argument and should return the value coerced to the appropriate type. The method may raise an exception if there are any problems parsing the string.

Alternately an optional method may be supplied (see the coerce_with option of Dsl::Parameters#requires). This may be any class or object implementing parse or call, with the same contract as described above.

Type Checking


Calls to coerced? will consult this class to check that the coerced value produced above is in fact of the expected type. By default this class performs a basic check against the type supplied, but this behaviour will be overridden if the class implements a class-level coerced? or parsed? method. This method will receive a single parameter that is the coerced value and should return true if the value meets type expectations. Arbitrary assertions may be made here but the grape validation system should be preferred.

Alternately a proc or other object responding to call may be supplied in place of a type. This should implement the same contract as coerced?, and must be supplied with a coercion method.

Direct Known Subclasses

CustomTypeCollectionCoercer

Instance Method Summary collapse

Constructor Details

#initialize(type, method = nil) ⇒ CustomTypeCoercer

A new coercer for the given type specification and coercion method.

Parameters:

  • type (Class, #coerced?, #parsed?, #call?)

    specifier for the target type. See class docs.

  • method (#parse, #call) (defaults to: nil)

    optional coercion method. See class docs.



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

def initialize(type, method = nil)
  coercion_method = infer_coercion_method type, method
  @method = enforce_symbolized_keys type, coercion_method
  @type_check = infer_type_check(type)
end

Instance Method Details

#call(val) ⇒ Object

Coerces the given value.

Parameters:

  • value (String)

    value to be coerced, in grape this should always be a string.

Returns:

  • (Object)

    the coerced result



54
55
56
57
58
59
60
61
# File 'lib/grape/validations/types/custom_type_coercer.rb', line 54

def call(val)
  coerced_val = @method.call(val)

  return coerced_val if coerced_val.is_a?(InvalidValue)
  return InvalidValue.new unless coerced?(coerced_val)

  coerced_val
end

#coerced?(val) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/grape/validations/types/custom_type_coercer.rb', line 63

def coerced?(val)
  val.nil? || @type_check.call(val)
end