So often, I find myself writing code as follows:
song.rb:
:before_save :cache_sortable_name
private
def cache_sortable_name
return unless name_changed?
self.sortable_name = name.sub(/^(the|a|an)\s+/i, '')
end
Ie, I have a database column sortable_namethat stores denormalized data for convenience, and I want to populate it whenever the model name changes.
I would like to be able to encapsulate this logic in a construct such as
:cache_in_database :sortable_name do
name.sub(/^(the|a|an)\s+/i, '')
end
or something like that. Does it exist?
source
share