Class: Grape::Validations::Validators::CoerceValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/grape/validations/validators/coerce_validator.rb

Instance Attribute Summary

Attributes inherited from Base

#attrs

Instance Method Summary collapse

Methods inherited from Base

default_message_key, inherited, #validate, #validate!

Methods included from Util::FreezeOnNew

#new

Constructor Details

#initialize(attrs, options, required, scope, opts) ⇒ CoerceValidator

Returns a new instance of CoerceValidator.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/grape/validations/validators/coerce_validator.rb', line 9

def initialize(attrs, options, required, scope, opts)
  super

  @exception_message = options.message if options.message

  raw_type = options.type
  type = hash_like?(raw_type) ? raw_type[:value] : raw_type
  @converter =
    if type.is_a?(Grape::Validations::Types::VariantCollectionCoercer)
      type
    else
      Types.build_coercer(type, method: options.coerce_method)
    end
end

Instance Method Details

#validate_param!(attr_name, params) ⇒ Object

The attribute is read once and held: coerce_value only ever sees the value, never the Hash, so the two further reads the identity check used to make came back with the same object -- through a HashWithIndifferentAccess key conversion each time, for every coerced attribute of every request.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/grape/validations/validators/coerce_validator.rb', line 29

def validate_param!(attr_name, params)
  validation_error!(attr_name) unless hash_like?(params)

  value = params[attr_name]
  new_value = coerce_value(value)

  validation_error!(attr_name, new_value.message || exception_message) if new_value.is_a?(Types::InvalidValue)

  # Don't assign a value if it is identical. It fixes a problem with Hashie::Mash
  # which looses wrappers for hashes and arrays after reassigning values
  #
  #     h = Hashie::Mash.new(list: [1, 2, 3, 4])
  #     => #<Hashie::Mash list=#<Hashie::Array [1, 2, 3, 4]>>
  #     list = h.list
  #     h[:list] = list
  #     h
  #     => #<Hashie::Mash list=[1, 2, 3, 4]>
  return if value.instance_of?(new_value.class) && value == new_value

  params[attr_name] = new_value
end