Module: ActiveModel::Validations::Callbacks::ClassMethods

Defined in:
lib/active_model/validations/callbacks.rb

Instance Method Summary collapse

Instance Method Details

#after_validation(*args, &block) ⇒ Object

Defines a callback that will get called right after validation.

class Person
  include ActiveModel::Validations
  include ActiveModel::Validations::Callbacks

  attr_accessor :name, :status

  validates_presence_of :name

  after_validation :set_status

  private

  def set_status
    self.status = errors.empty?
  end
end

person = Person.new
person.name = ''
person.valid? # => false
person.status # => false
person.name = 'bob'
person.valid? # => true
person.status # => true


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/active_model/validations/callbacks.rb', line 97

def after_validation(*args, &block)
  options = args.extract_options!
  options = options.dup
  options[:prepend] = true

  if options.key?(:on)
    options[:on] = Array(options[:on])
    options[:if] = Array(options[:if])
    options[:if].unshift ->(o) {
      !(options[:on] & Array(o.validation_context)).empty?
    }
  end

  set_callback(:validation, :after, *args, options, &block)
end

#before_validation(*args, &block) ⇒ Object

Defines a callback that will get called right before validation.

class Person
  include ActiveModel::Validations
  include ActiveModel::Validations::Callbacks

  attr_accessor :name

  validates_length_of :name, maximum: 6

  before_validation :remove_whitespaces

  private

  def remove_whitespaces
    name.strip!
  end
end

person = Person.new
person.name = '  bob  '
person.valid? # => true
person.name   # => "bob"


56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/active_model/validations/callbacks.rb', line 56

def before_validation(*args, &block)
  options = args.extract_options!

  if options.key?(:on)
    options = options.dup
    options[:on] = Array(options[:on])
    options[:if] = Array(options[:if])
    options[:if].unshift ->(o) {
      !(options[:on] & Array(o.validation_context)).empty?
    }
  end

  set_callback(:validation, :before, *args, options, &block)
end