Class: AttributeGuard::LockedAttributesValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
lib/attribute_guard.rb

Overview

Validator that checks for changes to locked attributes.

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/attribute_guard.rb', line 49

def validate(record)
  return if record.new_record?

  record.class.send(:locked_attributes).each do |attribute, params|
    if record.changes.include?(attribute) && record.attribute_locked?(attribute)
      message, mode = params
      if mode == :warn
        record&.logger&.warn("Changed locked attribute #{attribute} on #{record.class.name} with id #{record.id}")
      elsif mode.is_a?(Proc)
        mode.call(record, attribute)
      else
        record.errors.add(attribute, message)
      end
    end
  end
end