Assume you want to do some low level caching in Rails (with memcached, for example) and that you'd like to have just 1 call somewhere in your app, like...

Rails.cache.fetch('books', expires_in: 1.day) do
  Book.offset(offset)
      .limit(limit)
      .select('title, author, number_of_pages')
      .all
end

...to warm up your cache when you boot your app, so you can just use a simple call like...

Rails.cache.read('books')

...anywhere and multiple times throughout your app (in views, controllers, helpers...) to access this "books" collection.

Where should one put the initial "fetch" call to make it work?

有帮助吗?

解决方案

After your comment I want to clear up a couple of things.

You should always be using fetch if you require a result to come back. Wrap the call in a class method inside Book for easy access:

class Book
  def self.cached_books 
    Rails.cache.fetch < ... > 
  end
end

You can have a different method forcing the cache to be recreated:

def self.write_book_cache
     Rails.cache.write < ... > 
   end
end

Then in your initializer, or in a rake task, you can just do:

Book.write_book_cache

This seems more maintainable to me, while keeping the succinct call to the cache in the rest of your code.

其他提示

My first thought would be to put it in an initializer - probably one specifically for the purpose (/config/initializers/init_cache.rb, or something similar).

It should be executed automatically (by virtue of being in the initializers folder) when the app starts up.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top