class Grape::Validations::Types::PrimitiveCoercer
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.
Constants
- MAPPING
- STRICT_MAPPING
Attributes
type[R]
Public Class Methods
new(type, strict = false)
click to toggle source
Calls superclass method
Grape::Validations::Types::DryTypeCoercer::new
# File lib/grape/validations/types/primitive_coercer.rb, line 25 def initialize(type, strict = false) super @type = type @coercer = if strict STRICT_MAPPING.fetch(type) { scope.const_get(type.name) } else MAPPING.fetch(type) { scope.const_get(type.name) } end end
Public Instance Methods
call(val)
click to toggle source
Calls superclass method
Grape::Validations::Types::DryTypeCoercer#call
# File lib/grape/validations/types/primitive_coercer.rb, line 37 def call(val) return InvalidValue.new if reject?(val) return nil if val.nil? || treat_as_nil?(val) super end
Protected Instance Methods
reject?(val)
click to toggle source
This method maintains logic which was defined by Virtus. For example, dry-types is ok to convert an array or a hash to a string, it is supported, but Virtus wouldn't accept it. So, this method only exists to not introduce breaking changes.
# File lib/grape/validations/types/primitive_coercer.rb, line 52 def reject?(val) (val.is_a?(Array) && type == String) || (val.is_a?(String) && type == Hash) || (val.is_a?(Hash) && type == String) end
treat_as_nil?(val)
click to toggle source
Dry-Types treats an empty string as invalid. However, Grape
considers an empty string as absence of a value and coerces it into nil. See a discussion there github.com/ruby-grape/grape/pull/2045
# File lib/grape/validations/types/primitive_coercer.rb, line 61 def treat_as_nil?(val) val == '' && type != String end