Back to Posts List


A missing Rails callback?: fire a callback when an attribute has changed

Rails callbacks are awesome, it’s probably the most magical piece of code (aside from the demonic initializer) that i have seen in the source and we all use it in our controllers and models to enforce some DRY code and conventions over your application.

Lately, i came into realize, that there might be a missing callback in Rails. an when_attribute_changed callback that fires when you change an attribute.
Thanks to the ActiveRecord::Dirty magic, it’s very easy to be aware of where and when an attribute was changed and maybe try to wrap that out, but i was looking for something more accurate that wouldn’t require me to invoke changed? on every attribute.

So after digging a while in the Rails source code (Thanks to the Bugmash, it’s pretty easy to navigate through nowadays), i found that he base attribute handling is done with the write_attribute method so you should be ear-dropping into it.

This is a module that binds the attribute_changed custom callback and fires it off on when an attribute is changed. The default method that handles this exception is named flag_attribute_changed, but you can overwrite it as you like

although this is a nice roundup, i still haven’t found a way to restrict it to apply only on specific attributes. open to ideas.


blog comments powered by Disqus

I Don't have cookies.


Variable Value
{ '' => [ '#rubyonrails', '#railsbridge', '#ruby', '#mootools' ]}

You're seeing this error because I think it is funny.