Module: ActiveModel::Validations::Callbacks::ClassMethods
Relationships & Source Files | |
Defined in: | activemodel/lib/active_model/validations/callbacks.rb |
Instance Method Summary
-
#after_validation(*args, &block)
Defines a callback that will get called right after validation.
-
#before_validation(*args, &block)
Defines a callback that will get called right before validation.
- #set_options_for_callback(options) private
Instance Method Details
#after_validation(*args, &block)
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
# File 'activemodel/lib/active_model/validations/callbacks.rb', line 88
def after_validation(*args, &block) = args. = .dup [:prepend] = true ( ) set_callback(:validation, :after, *args, , &block) end
#before_validation(*args, &block)
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"
# File 'activemodel/lib/active_model/validations/callbacks.rb', line 55
def before_validation(*args, &block) = args. ( ) set_callback(:validation, :before, *args, , &block) end
#set_options_for_callback(options) (private)
[ GitHub ]# File 'activemodel/lib/active_model/validations/callbacks.rb', line 99
def ( ) if .key?(:on) [:on] = Array( [:on]) [:if] = [ ->(o) { [:on].intersect?(Array(o.validation_context)) }, * [:if] ] end end