Class: ChangeValidator

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ ChangeValidator

Enforce/prevent attribute change

Example: Make attribute immutable once saved validates :attribute, change: false, on: :update

Example: Force attribute change on every save validates :attribute, change: true



11
12
13
14
# File 'lib/change_validator.rb', line 11

def initialize(options)
  options[:change] = !(options[:with] === false)
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



16
17
18
19
20
# File 'lib/change_validator.rb', line 16

def validate_each(record, attribute, value)
  unless record.public_send(:"#{attribute}_changed?") == options[:change]
    record.errors[attribute] << ("#{options[:change] ? 'must' : 'cannot'} be modified")
  end
end