Created
November 17, 2011 03:32
-
-
Save JangoSteve/1372299 to your computer and use it in GitHub Desktop.
Automatically cache pages in Rails, put this in /lib/tasks/cache.rake
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See rails source: | |
# https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/caching/pages.rb | |
# | |
# Turn on caching in development, by changing this line to true in config/environments/development.rb: | |
# | |
# config.action_controller.perform_caching = true | |
# | |
# Then run: | |
# | |
# bundle exec rake pages:cache | |
# | |
# All cached pages will be in /public/path_name/xxxx.html | |
namespace :pages do | |
desc "Cache ALL the pages!" | |
task :cache => :environment do | |
# First, let's instantiate a new session so we can `get` our paths, | |
# just like if we were writing an integration test | |
app = ActionDispatch::Integration::Session.new(Rails.application) | |
# Now, we'll loop through each path we want to cache | |
%w( /index /about /contact /products /products/cool_thing /products/other_cool_thing ).each do |path| | |
# Get the path | |
app.get path | |
# Let's figure out the file path/name to which we're saving the file | |
file_path = "/cache/#{path.gsub('/', '_')[1,path.length]}" | |
# And now let's cache the response body HTML, using the ActionController's | |
ApplicationController.cache_page(app.response.body, file_path) | |
end | |
end | |
end |
This was a huge help! THANK YOU!
If you're doing this as part of a build/deploy you may want to include:
app.https!
app.host! "www.exmaple.com" # replace with your domain!
Otherwise you may get root_url
and other uses of host
pointing at http://www.example.com
instead of your domain!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Page caching has been removed from the Rails 4 core. To get this to work there you need to include the
actionpack-page_caching
gem in your Gemfile.