Class: DatabaseValidations::DbPresenceValidator

Inherits:
ActiveRecord::Validations::PresenceValidator
  • Object
show all
Defined in:
lib/database_validations/lib/validators/db_presence_validator.rb

Constant Summary collapse

REFLECTION_MESSAGE =
ActiveRecord::VERSION::MAJOR < 5 ? :blank : :required

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ DbPresenceValidator

Returns a new instance of DbPresenceValidator.

Parameters:

  • options (Hash)


15
16
17
18
19
20
21
22
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 15

def initialize(options)
  @klass = options[:class]

  super

  Injector.inject(klass)
  Checkers::DbPresenceValidator.validate!(self)
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



5
6
7
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 5

def klass
  @klass
end

Class Method Details

.kindSymbol

Used to make 3rd party libraries work correctly

Returns:

  • (Symbol)


10
11
12
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 10

def self.kind
  :presence
end

Instance Method Details

#apply_error(instance, attribute) ⇒ Object



39
40
41
42
43
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 39

def apply_error(instance, attribute)
  # Helps to avoid querying the database when attribute is association
  instance.send("#{attribute}=", nil)
  instance.errors.add(attribute, :blank, message: REFLECTION_MESSAGE)
end

#validate(record) ⇒ Object

TODO: add support of optional db_belongs_to



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 25

def validate(record)
  if record._database_validations_fallback
    super
  else
    attributes.each do |attribute|
      reflection = record.class._reflect_on_association(attribute)

      next if reflection && record.public_send(reflection.foreign_key).present?

      validate_each(record, attribute, record.public_send(attribute))
    end
  end
end