Module: ActiveModel::Validations::Callbacks::ClassMethods
- Defined in:
- activemodel/lib/active_model/validations/callbacks.rb
Instance Method Summary collapse
-
#after_validation(*args, &block) ⇒ Object
Defines a callback that will get called right after validation happens.
-
#before_validation(*args, &block) ⇒ Object
Defines a callback that will get called right before validation happens.
Instance Method Details
#after_validation(*args, &block) ⇒ Object
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
95 96 97 98 99 100 101 102 103 104 |
# File 'activemodel/lib/active_model/validations/callbacks.rb', line 95 def after_validation(*args, &block) = args. [:prepend] = true [:if] = Array([:if]) if [:on] [:on] = Array([:on]) [:if].unshift("#{[:on]}.include? self.validation_context") end set_callback(:validation, :after, *(args << ), &block) end |
#before_validation(*args, &block) ⇒ Object
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"
56 57 58 59 60 61 62 63 64 65 66 |
# File 'activemodel/lib/active_model/validations/callbacks.rb', line 56 def before_validation(*args, &block) = args.last if .is_a?(Hash) && [:on] [:if] = Array([:if]) [:on] = Array([:on]) [:if].unshift lambda { |o| [:on].include? o.validation_context } end set_callback(:validation, :before, *args, &block) end |