7. Callbacks
• Methods : protected or private
• Before or after certain moments of an
object’s life cycle
• 6create, save, update, delete, validate, load
:
events
• Register using a macro-style class method
★ as an ordinary method or
★ supply as a block
8. Available Callbacks
★ Creating an Object ★ Updating an Object ★ Destroying an Object
• before_validation • before_validation • before_destroy
• after_validation • after_validation • around_destroy
• before_save • before_save • after_destroy
• before_create • before_update
• around_create • around_update
• after_create • after_update
• after_save • after_save
DB
Validation
Create
Save
Update
Destroy
9. After_find
> After_initialize
class User < ActiveRecord::Base
after_initialize do |user|
puts "You have initialized an object!"
end
after_find do |user|
puts "You have found an object!"
end
end
>> User.new
You have initialized an object!
=> #<User id: nil>
>> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>
15. Conditional
Callbacks
• As with validations
★ Using :if and :unless with a Symbol
★ Using :if and :unless with a String
★ Using :if and :unless with a Proc
16. Conditional
Callbacks
as a symbol
as a string
as a Proc
* multiple conditions possible!
17. Callback Classes
• To reuse callback methods for other models
as an instance method
a model object
instance
method
19. Observers
• Similar to callbacks
• for the callbacks with the code that isn’t
directly related the model
• without changing the code of the model
• ex. sending confirmation email after user
registration
26. Macro-style class methods :
As Ordinary
Methods
class User ActiveRecord::Base
validates :login, :email, :presence = true
before_validation :ensure_login_has_a_value
protected
def ensure_login_has_a_value
if login.nil?
self.login = email unless email.blank?
end
end
27. public/protected/private
parent
pr
class iv
at child
e_
m
private
et
ho
class
protected
public d
private
(sel
f.)p
protected
rote
public
ed_ ct
met
hod
http://stackoverflow.com/questions/4495078/protected-and-private-methods-in-rails
28. Macro-style class methods :
A Block
class User ActiveRecord::Base
validates :login, :email, :presence = true
before_create do |user|
user.name = user.login.capitalize
if user.name.blank?
end