Class: Grape::Validations::CoerceValidator

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

Instance Attribute Summary

Attributes inherited from Base

#attrs

Instance Method Summary collapse

Methods inherited from Base

convert_to_short_name, #fail_fast?, inherited, #message, #options_key?, #validate!

Constructor Details

#initialize(*_args) ⇒ CoerceValidator

Returns a new instance of CoerceValidator.



20
21
22
23
24
25
26
27
28
# File 'lib/grape/validations/validators/coerce.rb', line 20

def initialize(*_args)
  super

  @converter = if type.is_a?(Grape::Validations::Types::VariantCollectionCoercer)
                 type
               else
                 Types.build_coercer(type, method: @option[:method])
               end
end

Instance Method Details

#validate(request) ⇒ Object



30
31
32
# File 'lib/grape/validations/validators/coerce.rb', line 30

def validate(request)
  super
end

#validate_param!(attr_name, params) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/grape/validations/validators/coerce.rb', line 34

def validate_param!(attr_name, params)
  raise validation_exception(attr_name) unless params.is_a? Hash

  new_value = coerce_value(params[attr_name])

  raise validation_exception(attr_name) unless valid_type?(new_value)

  # 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].class == new_value.class && params[attr_name] == new_value

  params[attr_name] = new_value
end