Manually Generates Rails Cache Key

I am trying to use isolated workers to create and manage my cache. I would like these workers to be as thin as possible. (do not use rails)

I'm having trouble faking the cache keys created by rails

In my opinion, I have the following:

cache ["comments", @ama] 

I am trying to replicate the key that it creates with the following:

 updated_at = Time.parse(row['updated_at']) timestamp = updated_at.utc.strftime('%Y%m%d%H%M%S') cache_key = "views/comments/amas/#{row['id']}-#{timestamp}" 

What will produce:

 views/comments/amas/432-20121227010114 

The cache from this key is empty.

Either I'm not formatting my key correctly, or the cache is missing. I am 95% sure that there is a cache that I am looking for.

(I can click the cache with the key, for example, "test", and then return it. Therefore, I know that caching works)

Useful links:

Useful information:

  • The cache server is not local, and yes, I point to it.
  • Even if the key did not exist, when I load the page into production, the key and cache will be built in place. Which I tried.
  • using Rails 4.0.0
+4
source share
2 answers

Pattern cache keys are as follows:

 views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9 ^class ^id ^updated_at ^template tree digest 

Link: http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html#method-i-cache

+4
source

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.

+5
source

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


All Articles