Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why callbacks for the after_find and after_initialize events is to define them as methods?

The only way to define callbacks for the after_find and after_initialize events is to define them as methods. If you try declaring them as handlers using the second technique, they’ll be silently ignored.

Can anybody explain why is it so?

Why specifically for these two callbacks?

EDIT

From the book:-- Rails has to use reflec- tion to determine whether there are callbacks to be invoked. When doing real database operations, the cost of doing this is normally not significant com- pared to the database overhead. However, a single database select statement could return hundreds of rows, and both callbacks would have to be invoked for each. This slows the query down significantly. The Rails team decided that performance trumps consistency in this case. What the hell...!!!! Thats all.. Just this as explanation...!!!

like image 716
Mohit Jain Avatar asked Nov 05 '22 13:11

Mohit Jain


1 Answers

From the API:

The after_find and after_initialize exceptions

Because after_find and after_initialize are called for each object found and instantiated by a finder, such as Base.find(:all), we‘ve had to implement a simple performance constraint (50% more speed on a simple test case). Unlike all the other callbacks, after_find and after_initialize will only be run if an explicit implementation is defined (def after_find). In that case, all of the callback types will be called.

like image 113
Gareth Avatar answered Nov 11 '22 05:11

Gareth