Preserve Semantics in Callbacks
Many people tend to place logic within a method named for the callback (e.g. after_destroy). This works fine, but tends to be less maintainable, in my opinion.
You basically have a method called after_destroy (or whatever), but you don’t readily know what its doing. A better approach is to write an intention-revealing named method and reference that in the reference to your callback method. You then can see through the method name what is happening in response to the event. Further, the method can be used at other times. This approach restores a bit of maintainability to your code.
I have included an example of this approach below. You’ll have to visualize the before version — I don’t like posting less maintainable code because sometimes people skim it without reading and take it as good code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Rating < ActiveRecord::Base # ---- Associations ---- # The rateable that was rated. belongs_to :rateable # ---- Callbacks ---- after_destroy :update_ratings # ---- Calculations ---- # Updates the parent's rating count and average rating. def update_ratings rateable.update_ratings end end |