Precompile / preload cached fragments in Rails

Using Rails 3.1.1 and Herkou

I have 1,000 products in my application. All of them have a very slow controller, which is effectively solved by caching fragments. Although the data does not change very often, it should still expire (which I do by sweeping) periodically, in my case, once a week.

Now, after sweeping the cached views, I don’t want my users to create new fragments, trying to access the products one by one (it takes about 6-8 seconds on first boot, 2-3 seconds for caching load). I suppose I can do this with a kind of script that will load each page of the Product one at a time and thus make the server create these fragments.

I can imagine that this can be handled in three ways:

  • Run a script on my local machine that will try to access each URL using some kind of get-down command. Downside: Not very pretty and will affect visitor statistics in a way that I would not want.

  • Run the same type of script on the server after the cleaner, which will load each Product. How can I do this in this case?

  • Using the smart Rails command to do this automatically. Is there such an elegant team?

+4
source share
2 answers

I made this script and it works. "Product.slug" is because I have set friendly_id. It will create URL variables with names like www.mydomain.com/productabc-123/ that Nokogiri will read (this solution requires the Nokogiri stone).

PLEASE PLEASE CONTACT THAT I SWITCHED FROM THE FRAGMENT PICTURE TO ACCEPTING ACTIONS IN THIS SOLUTION (as opposed to the question where I use fragment caching). An important difference between this is the cache check if Rails.cache.exist?('views/www.mydomain.com/' + product.slug) . For fragment_caching, there should be a fragment name instead.

 require 'nokogiri' require 'open-uri' Product.all.each do |product| url = 'http://www.mydomain.com/' + product.slug begin if Rails.cache.exist?('views/www.mydomain.com/' + product.slug) puts url + " is already in cache" else doc = Nokogiri::HTML(open(url)) puts "Reads " + url # Verifies if the caching worked. Only for trouble shooting if Rails.cache.exist?('views/www.mydomain.com/' + product.slug) puts "--->" + url + " is NOW in the cache" else puts "--->" + url + " is still not in the cache!" end sleep 1 end rescue puts 'Normal rescue of ' + url rescue Timeout::Error puts 'Timeout rescue of ' + url puts 'Sleep for 5 sec' sleep 5 retry end end 
0
source

Create a script that works like a rake task, or better yet an employee who starts and wraps the page. There is no need to turn on the gem when you can just call curl

 `curl -A "CacheRefresher" #{ENV['HOSTNAME']}/api/v1/#{klass.name.underscore.pluralize}/#{id} >/dev/null 2>&1` 
0
source

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


All Articles