Class: Rbdantic::Validators::Types::Hash

Inherits:
Base
  • Object
show all
Defined in:
lib/rbdantic/validators/types/hash.rb

Instance Attribute Summary

Attributes inherited from Base

#constraints

Instance Method Summary collapse

Methods inherited from Base

#initialize, #validate

Constructor Details

This class inherits a constructor from Rbdantic::Validators::Types::Base

Instance Method Details

#coerce(value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rbdantic/validators/types/hash.rb', line 23

def coerce(value)
  case value
  when ::Hash then value
  when ::Array
    value.to_h if value.all? { |item| item.is_a?(::Array) && item.length == 2 }
  when ::String
    begin
      parsed = JSON.parse(value)
      parsed if parsed.is_a?(::Hash)
    rescue JSON::ParserError; nil
    end
  else
    value.to_h if value.respond_to?(:to_h)
  end
end

#expected_type_nameObject



14
15
16
# File 'lib/rbdantic/validators/types/hash.rb', line 14

def expected_type_name
  "Hash"
end

#matches_type?(value) ⇒ Boolean

Returns:



10
11
12
# File 'lib/rbdantic/validators/types/hash.rb', line 10

def matches_type?(value)
  value.is_a?(::Hash)
end

#validate_constraints(value, errors, location, strict: false) ⇒ Object



18
19
20
21
# File 'lib/rbdantic/validators/types/hash.rb', line 18

def validate_constraints(value, errors, location, strict: false)
  validate_size(value, errors, location)
  value
end