module ActiveModel::Validations::Callbacks::ClassMethods

Public Instance Methods

after_validation(*args, &block) Show source
# File activemodel/lib/active_model/validations/callbacks.rb, line 95
def after_validation(*args, &block)
  options = args.extract_options!
  options[:prepend] = true
  options[:if] = Array(options[:if])
  if options[:on]
    options[:on] = Array(options[:on])
    options[:if].unshift ->(o) {
      options[:on].include? o.validation_context
    }
  end
  set_callback(:validation, :after, *(args << options), &block)
end

Defines a callback that will get called right after validation happens.

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
before_validation(*args, &block) Show source
# File activemodel/lib/active_model/validations/callbacks.rb, line 56
def before_validation(*args, &block)
  options = args.last
  if options.is_a?(Hash) && options[:on]
    options[:if] = Array(options[:if])
    options[:on] = Array(options[:on])
    options[:if].unshift ->(o) {
      options[:on].include? o.validation_context
    }
  end
  set_callback(:validation, :before, *args, &block)
end

Defines a callback that will get called right before validation happens.

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"

© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.