The most efficient way to implement low-level caching is to use the Rails.cache.fetch method. It will read the value from the cache, if available; otherwise it will execute the block passed to it and return the result:
You can manually set the cache key from the rails console (by typing "rails c" at the command prompt)
>> Rails.cache.fetch('answer') ==> "nil" >> Rails.cache.fetch('answer') {1 + 1} ==> 2 Rails.cache.fetch('answer') ==> 2
Consider the following example. The application has a product model with a class method that returns all items outside the warehouse, and an instance method that looks for the price of the product on a competing website. The data returned by these methods would be ideal for low-level caching:
# product.rb def Product.out_of_stock Rails.cache.fetch("out_of_stock_products", :expires_in => 5.minutes) do Product.all.joins(:inventory).conditions.where("inventory.quantity = 0") end end def competing_price Rails.cache.fetch("/product/#{id}-#{updated_at}/comp_price", :expires_in => 12.hours) do Competitor::API.find_price(id) end end
I think it will be useful for you.
Thanks.
source share