Class: ChangesValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/changes_validator.rb,
lib/changes_validator/version.rb

Defined Under Namespace

Classes: ConfigurationError

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initializeChangesValidator

Returns a new instance of ChangesValidator.



5
6
7
8
# File 'lib/changes_validator.rb', line 5

def initialize(*)
  super
  normalize_options
end

Instance Method Details

#ensure_supports_dirty(record) ⇒ Object



24
25
26
27
28
# File 'lib/changes_validator.rb', line 24

def ensure_supports_dirty(record)
  unless record.respond_to?(:changes)
    raise ConfigurationError, "ChangesValidator can only be applied to model with dirty support (ActiveModel::Dirty)"
  end
end

#normalize_optionsObject



32
33
34
35
36
# File 'lib/changes_validator.rb', line 32

def normalize_options
  unless options[:with]
    @options = {:with => options}
  end
end

#validate_each(record, attribute, value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/changes_validator.rb', line 10

def validate_each(record, attribute, value)
  ensure_supports_dirty(record)
  changes = record.changes[attribute.to_s]
  return unless changes
  changess = options[:with]
  start = changes.first
  destination = value

  allowed_changess = changess[start]
  if !allowed_changess || !Array(allowed_changess).map {|s| s.to_s }.include?(destination.to_s)
    record.errors.add(attribute, :changes, :old_value => start, :message => options[:message])
  end
end