On a particular, nameless, heterogenous project using ruby on rails, ant, and shell scripts, there was an instance where data was not being properly cleaned before going into the database (primarily due to user errors in property files which were used by ant to feed the database). As a result, the database was filled with extraneous spaces which were causing many issues. A perfect illustration of GIGO.
One problem was that there were multiple databases, each with their own data. By the time the issue was discovered, a fix was needed soonest, so the solution was less than elegant, but it does illustrate the use of callbacks in ActiveRecord:
module DbParanoia
# This is a really stupid thing to have to back-fit; it is making
# sure, however, that the users enter good data. We ensure that
# strings are stripped on read and write.
def trim_space
self.attributes.each do |attr|
attr.strip! if attr.instance_of? String
end
end
alias_method :after_find, :trim_space
alias_method :before_save, :trim_space
end
The above module is using the after_find and before_save callbacks to make sure that:
- Any spaces coming back from the database are trimmed.
- Any new records and/or updates will have the spaces trimmed.
You can use this method to perform pretty much any sort of validation or data manipulation of the data of an ActiveRecord class. Other callbacks include:
- after_create
- after_destroy
- after_save
- after_update
- after_validation
- after_validation_on_create
- after_validation_on_update
- before_create
- before_destroy
- before_save
- before_update
- before_validation
- before_validation_on_create
- before_validation_on_update
You can read more about ActiveRecord::Callbacks at http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html.