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, #fail_fast?, inherited, new, #validate, #validate!

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
# File 'lib/grape/validations/validators/coerce_validator.rb', line 9

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

  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[:method])
    end
end

Instance Method Details

#validate_param!(attr_name, params) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/grape/validations/validators/coerce_validator.rb', line 22

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

  new_value = coerce_value(params[attr_name])

  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 params[attr_name].instance_of?(new_value.class) && params[attr_name] == new_value

  params[attr_name] = new_value
end