Class: ValidationProfiler::Rules::ChildValidationRule

Inherits:
ValidationRule
  • Object
show all
Defined in:
lib/validation_profiler/rules/child_validation_rule.rb

Overview

Validation rule for child attributes

Instance Method Summary collapse

Methods inherited from ValidationRule

#get_field_value, #is_required?

Instance Method Details

#build_parent_field(parent, field) ⇒ Object



40
41
42
43
44
# File 'lib/validation_profiler/rules/child_validation_rule.rb', line 40

def build_parent_field(parent, field)
  return field.to_s if parent.nil?

  "#{parent}.#{field}"
end

#error_message(field, attributes = {}, parent = nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/validation_profiler/rules/child_validation_rule.rb', line 5

def error_message(field, attributes = {}, parent = nil)
  field_name = field.to_s
  field_name = "#{parent}.#{field}" unless parent.nil?

  # check if a custom error message has been specified in the attributes
  if attributes[:message].nil?
    # no custom error message has been specified so create the default message.
    "#{field_name} is required."
  else
    attributes[:message]
  end
end

#get_validation_profile(attributes, field) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/validation_profiler/rules/child_validation_rule.rb', line 46

def get_validation_profile(attributes, field)
  if attributes[:profile].nil?
    raise ValidationProfiler::Exceptions::InvalidValidationRuleAttributes
      .new(ValidationProfiler::Rules::ChildValidationRule, field)
  end

  attributes[:profile]
end

#validate(obj, field, attributes = {}, parent = nil) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/validation_profiler/rules/child_validation_rule.rb', line 18

def validate(obj, field, attributes = {}, parent = nil)
  # attempt to get the field value from the object
  field_value = get_field_value(obj, field)

  return true unless is_required?(field_value, attributes)
  return false if field_value.nil?
  return false if field_value.respond_to?(:empty?) && field_value.empty?

  validation_profile = get_validation_profile(attributes, field)
  parent_field = build_parent_field(parent, field)

  validate_field_value(field_value, validation_profile, parent_field)
end

#validate_field_value(field_value, profile, parent_field) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/validation_profiler/rules/child_validation_rule.rb', line 32

def validate_field_value(field_value, profile, parent_field)
  if field_value.is_a? Array
    field_value.map { |value| ValidationProfiler::Manager.new.validate(value, profile, parent_field) }
  else
    ValidationProfiler::Manager.new.validate(field_value, profile, parent_field)
  end
end