views:

84

answers:

1

So frequently I find myself writing code like this:

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

I.e., I have a sortable_name database column which holds denormalized data for convenience, and I want to populate it whenever the model's name changes.

I would like to be able to encapsulate this logic in a construct such as this

:cache_in_database :sortable_name do
  name.sub(/^(the|a|an)\s+/i, '')
end

or something. Does this exist?

+1  A: 

So... You want a callback called "cache_in_database" that takes an attribute and a block, and sets the attribute to the return value of the block before each save. Is that right?

I haven't heard of such a thing, but it would be an easy plugin to write. Just write a cache_in_database class method that takes the attribute and block parameter, creates a proc or method that does the assignment, and adds it to the before_save chain. The question to me is whether you do this so often that it's worth the added magic to save a line or so of code each time.

SFEley