Today I Learned

hashrocket A Hashrocket project

Conditional Callbacks

Rails has a method for triggering a callback conditionally: <column>_changed?. In the case of my current project, I want to trigger a Slack web hook only if a specific attribute, 'likes', has changed.

# app/models/post.rb
after_update :notify_slack, if: :likes_changed?

Of course, this logic could be moved into the callback method definition, but I like that it's stated upfront at the top of the class.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.