Active Record Callbacks
====
Based on guides.rubyonrails.org
Callbacks are methods that is
called in certain moment in a life-cicle of a object. Callbacks are triggered by a specific
operation over the Active Record Object.
Ways of calling a callback
- Creating a
methods. It can be set to run only in
some lifecicle events
class User
< ActiveRecord::Base
before_validation :normalize_name, on:
:create
# :on takes an array as well
after_validation :set_location, on: [
:create, :update ]
protected
def normalize_name
self.name = self.name.downcase.titleize
end
def set_location
self.location = LocationService.query(self)
end
end
- Creating a block
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
end
Running Callbacks
Callbacks are triggered
by using the following methods.
create
create!
decrement!
destroy
destroy!
destroy_all
increment!
save
save!
save(validate: false)
toggle!
update_attribute
update
update!
valid?
Calbacks for Creating
an Object
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
Calbacks for Updating
an Object
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
Calbacks for Destroying
an Object
before_destroy
around_destroy
after_destroy
Others callbacks
after_initialize
Run
then the Object is instantiated with new or loaded from DB.
after_find
Run
then the Object is loaded from DB.
after_find
is triggered by using the following finder methods:
all
first
find
find_by
find_by_*
find_by_*!
find_by_sql
last
Halting Execution
If an exception is
thrown, the operation is halted or Rolledback
Conditional Callbacks
:if or :unles
with a simbol
class Order
< ActiveRecord::Base
before_save :normalize_card_number, if:
:paid_with_card?
end
Using String
Used in a
short condition
class Order
< ActiveRecord::Base
before_save :normalize_card_number, if:
"paid_with_card?"
end
With a Proc
Used in a
short validation method
class Order
< ActiveRecord::Base
before_save :normalize_card_number,
if: Proc.new { |order|
order.paid_with_card? }
end
Multiple Callbacks
class Comment <
ActiveRecord::Base
after_create :send_email_to_author, if:
:author_wants_emails?,
unless: Proc.new { |comment|
comment.post.ignore_comments? }
end
Callbacks Classes
Transactionnal Callbacks
after_commit and
after_rollback. Similar to after_save,
but only execute after the changes are
commited or rolledback. Usefull when
system interacted with external applications.
It is called insede a
transaction block. If a exception is
thrown the callback is ignored, because they are called only after the
operation on DB is finished.
Nenhum comentário:
Postar um comentário