Cache of all models in the table

I need to cache (and expire) all models in a table.

For example, if I have a model called "Currency", I will have less than 10 possible currencies. Therefore, it would be nice to have:

class Currency < ActiveRecord::Base
  cache_all(:expire_in => 10.minutes)
end

so that

Currency.all
Currency.find_by_name("USD")

should not fall into the database.

Do you think this could be a good approach?

In addition, if you think it is better to use a model that is not backed by a database, comment on this. Please note that I would like to have an AR-style association.

+3
source share
1 answer

, , . , - Memoization, . , all find_by_name , .

. - .

class Currency < ActiveRecord::Base
  def self.all
    @all_cache ||= super.map(&:freeze) # freeze so you don't modify the cached objects
  end

  def self.find_by_name(name)
    all.detect { |c| c.name.to_s.downcase == name.to_s.downcase }
  end

  def self.flush_all_cache
    @all_cache = nil
  end
end

, , .

+7

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


All Articles