Denormalization abstraction in Rails?

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?

+3
source share
1 answer

So ... you want a callback called "cache_in_database" that takes an attribute and a block, and sets the attribute to the returned value of the block before each save. Is it correct?

, . cache_in_database, , proc , , before_save. , , , .

+1

Source: https://habr.com/ru/post/1718507/


All Articles