Class: ValidateParams::Validatable::ParamBuilder::Validation

Inherits:
Struct
  • Object
show all
Defined in:
lib/validate_params/param_builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#childrenObject

Returns the value of attribute children



6
7
8
# File 'lib/validate_params/param_builder.rb', line 6

def children
  @children
end

#fieldObject

Returns the value of attribute field



6
7
8
# File 'lib/validate_params/param_builder.rb', line 6

def field
  @field
end

#optionsObject

Returns the value of attribute options



6
7
8
# File 'lib/validate_params/param_builder.rb', line 6

def options
  @options
end

#parentObject

Returns the value of attribute parent



6
7
8
# File 'lib/validate_params/param_builder.rb', line 6

def parent
  @parent
end

#typeObject

Returns the value of attribute type



6
7
8
# File 'lib/validate_params/param_builder.rb', line 6

def type
  @type
end

Instance Method Details

#valid?(value, errors) ⇒ Boolean



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/validate_params/param_builder.rb', line 7

def valid?(value, errors)
  ParamValidator.call(
    validation: self,
    value: value,
    errors: errors
  )

  if children.any?
    case type.to_s
    when "Hash"
      children.each do |child|
        child_value = value[child.field] if value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
        child.valid?(child_value, errors)
      end
    when "Array"
      values = value ? Array.wrap(value) : [nil]
      values.each do |item|
        children.each do |child|
          child_value = item[child.field] if item.is_a?(Hash) ||
            item.is_a?(ActionController::Parameters) ||
            item.is_a?(Array)
          child.valid?(child_value, errors)
        end
      end
    else
      raise "Unexpected type: #{type}"
    end
  end

  errors.empty?
end