when is around_create callback code executed, in what situations we should use it?
相关问题
- Disable Browser onUnload on certain links?
- Eager-loading association count with Arel (Rails 3
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
相关文章
- laravel create model from custom stub when using p
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- How to create a CFuncType in Python
- “No explicit conversion of Symbol into String” for
- Rspec controller error expecting <“index”> but
- Factory_girl has_one relation with validates_prese
Simpler and neat explanation about around callback I found, is given below
The around_* callback is called around the action and inside the before_* and after_* actions. For example:
Originally posted here
Had this question, too, and have now found the answer:
around_create
allows you to basically do both abefore_create
and anafter_create
in one method. You have to useyield
to execute the save in between.Besides Tom Harrison Jr's answer about logging and monitoring, I'm finding that the key differentiator is to gain control over whether or not the operation runs at all. Otherwise, you can implement your own
before_*
andafter_*
callbacks to do the same thing.Take
around_update
, for example. Let's say you have a case where you don't want the update to run. For example, I'm building a gem that saves drafts in anotherdrafts
table but doesn't save certain updates to the "master" table.The details of the
update_base_record?
method referenced here don't really matter. You can see that the update operation simply won't run if that method doesn't evaluate totrue
.A classic use-case for the "around" filters is to measure performance, or log or do other state monitoring or modification.
around_create
is called when a model with thenew?
flag is saved. It can be used to add data to add/change values of the model, call other methods, etc... I cannot thnk of a specific use case for this call-back but it completes a set of "before, after, around" call-backs for the create action. There is a similar "before, after, around" call back set for the find, update, save, and delete events.Just found one use case for me:
Imagine a situation with polymorphic watcher and the watcher in some cases needs to perform action before save and in other cases after it.
With around filter you can capture save action in a block and run it when you need.