Class: ValidatesAssociatedWithContext::AssociatedWithContextValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validates_associated_with_context/associated_with_context.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ AssociatedWithContextValidator

Returns a new instance of AssociatedWithContextValidator.



7
8
9
10
11
12
13
# File 'lib/validates_associated_with_context/associated_with_context.rb', line 7

def initialize(options)
  @context = options.delete(:context)
  @inherit_context = options.delete(:inherit_context)
  @bubble_messages = options.delete(:bubble_messages)

  super
end

Instance Attribute Details

#bubble_messagesObject (readonly)

Returns the value of attribute bubble_messages.



5
6
7
# File 'lib/validates_associated_with_context/associated_with_context.rb', line 5

def bubble_messages
  @bubble_messages
end

#inherit_contextObject (readonly)

Returns the value of attribute inherit_context.



5
6
7
# File 'lib/validates_associated_with_context/associated_with_context.rb', line 5

def inherit_context
  @inherit_context
end

Instance Method Details

#context(record) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/validates_associated_with_context/associated_with_context.rb', line 15

def context(record)
  return record.validation_context if inherit_context

  if @context.respond_to?(:call)
    @context.call record
  else
    @context
  end
end

#validate_each(record, attribute, value) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/validates_associated_with_context/associated_with_context.rb', line 25

def validate_each(record, attribute, value)
  validation_context = context(record)

  if bubble_messages
    Array(value).each do |r|
      next if valid_object?(r, validation_context)

      if r.errors.any?
        r.errors.each do |error|
          record.errors.add(attribute, error.full_message, **options.merge(value: r))
        end
      else
        record.errors.add(attribute, :invalid, **options.merge(value: r))
      end
    end
  else
    if Array(value).reject { |r| valid_object?(r, validation_context) }.any?
      record.errors.add(attribute, :invalid, **options.merge(value: value))
    end
  end
end