Friday, February 27, 2015

Callbacks in pure ruby - prepend over alias_method

I had a need to encrypt a password before an object was saved.  I searched around to find a gem that implemented callbacks in ruby but didn't find much.  I did come across this stack over flow post with some good recommendations.  Using the magical method_added worked pretty well for a single module included into a class.  However it didn't work so well when I had multiple modules inside my gem that were included in a class.  The original code looked something like this:

This worked until I had a save method in my class and a save method in my module. The callback no longer worked.  The methods got stomped on when they were included.  So now onto the awesome prepend Module method.  This is a much cleaner way of prepending your module with an anonymous module that includes your method.  It is then properly in your call hierarchy so you can call it via super!

Here is what the callback code looks like now.  I feel like it is very readable and easy to comprehend:

Feel free to post comments and feedback :)

No comments:

Post a Comment