Class: Grape::Validations::Validators::CoerceValidator
- Defined in:
- lib/grape/validations/validators/coerce_validator.rb
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
-
#initialize(attrs, options, required, scope, opts) ⇒ CoerceValidator
constructor
A new instance of CoerceValidator.
- #validate_param!(attr_name, params) ⇒ Object
Methods inherited from Base
#fail_fast?, inherited, #message, #options_key?, #validate, #validate!
Constructor Details
#initialize(attrs, options, required, scope, opts) ⇒ CoerceValidator
Returns a new instance of CoerceValidator.
7 8 9 10 11 12 13 14 15 |
# File 'lib/grape/validations/validators/coerce_validator.rb', line 7 def initialize(attrs, , required, scope, opts) 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_param!(attr_name, params) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/grape/validations/validators/coerce_validator.rb', line 17 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, new_value.) 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].instance_of?(new_value.class) && params[attr_name] == new_value params[attr_name] = new_value end |