Class: Rbdantic::Validators::Types::Array

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

Instance Attribute Summary collapse

Attributes inherited from Base

#constraints

Instance Method Summary collapse

Methods inherited from Base

#validate

Constructor Details

#initialize(element_type: nil, **constraints) ⇒ Array

Returns a new instance of Array.



12
13
14
15
16
# File 'lib/rbdantic/validators/types/array.rb', line 12

def initialize(element_type: nil, **constraints)
  super(**constraints)
  @element_type = element_type
  @item_validator = Types.create_validator(element_type) if element_type
end

Instance Attribute Details

#element_typeObject (readonly)

Returns the value of attribute element_type.



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

def element_type
  @element_type
end

#item_validatorObject (readonly)

Returns the value of attribute item_validator.



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

def item_validator
  @item_validator
end

Instance Method Details

#coerce(value) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rbdantic/validators/types/array.rb', line 32

def coerce(value)
  case value
  when ::String
    begin
      parsed = JSON.parse(value)
      parsed if parsed.is_a?(::Array)
    rescue JSON::ParserError; nil
    end
  else
    value.respond_to?(:to_a) ? value.to_a : nil
  end
end

#expected_type_nameObject



22
23
24
# File 'lib/rbdantic/validators/types/array.rb', line 22

def expected_type_name
  "Array"
end

#matches_type?(value) ⇒ Boolean

Returns:



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

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

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



26
27
28
29
30
# File 'lib/rbdantic/validators/types/array.rb', line 26

def validate_constraints(value, errors, location, strict: false)
  validate_length(value, errors, location)
  validate_unique(value, errors, location)
  validate_items(value, errors, location, strict: strict)
end