Callbacks are a great technique for achieving simplicity and flexibility. Callbacks provide a means of hooking into an ActiveRecord object’s life-cycle. A hook is a technique that lets you trap some Ruby event with ActiveRecord, such as object creation. Callbacks are hooks that allow you to trigger logic before or after an alteration of the object state. Callback functions minimizing the length of codes in controllers.
There are four types of callbacks accepted by the callback macros:
- Method references (symbol)
- Callback objects
- Inline methods (using a proc)
- Inline eval methods (using a string) – deprecated.
Method references and callback objects are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins) and inline eval methods are deprecated.
The method reference callbacks work by specifying a protected or private method available in the object, like this:
class Post < ActiveRecord::Base
View original post 182 more words