public
Last active

Rake task to precompile static pages in app/views/static/ folder

  • Download Gist
precompile_static_pages.rake
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
module StaticHelpers
def action_for_template(template)
File.basename(template).sub(/\.html\.haml$/, '')
end
end
 
namespace :static do
desc "Precompile static pages at public/*.html"
task :precompile do
include StaticHelpers
require 'fileutils'
 
# Do the dance of my people
if ENV["RAILS_ENV"].to_s.empty?
ENV["RAILS_ENV"] = "production"
system $0, 'static:precompile'
else
# Set up environment if Application is not yet initialized
unless Rails.application.instance_variable_get('@initialized')
Rake::Task["environment"].invoke
end
 
app = ActionDispatch::Integration::Session.new(Rails.application)
base_url = "http://www.example.com"
 
actions = Dir.glob(Rails.root.join('app/views/static/[^_]*\.html\.haml')).map do |template|
action_for_template(template)
end
actions << '' # Root route ('/')
 
actions.each do |action|
output_file = action == '' ? 'index' : action
puts "Rendering /#{action} => public/#{output_file}.html"
 
app.get "#{base_url}/#{action}"
 
ApplicationController.cache_page app.response.body, "/#{output_file}.html"
end
 
puts "Static pages generated."
end
end
 
# Note: If you remove a view template from app/views/static,
# it's precompiled page will not be deleted from public/
desc "Delete precompiled static pages"
task :clean do
include StaticHelpers
 
actions = Dir.glob(Rails.root.join('app/views/static/[^_]*\.html\.haml')).map do |t|
action_for_template(t)
end
actions << 'index'
 
actions.each do |action|
%w(.html .html.gz).each do |ext|
cached_page = Rails.root.join("public/#{action}#{ext}")
if File.exists?(cached_page) || File.symlink?(cached_page)
puts "Deleting public/#{action}#{ext}"
File.delete cached_page
end
end
end
 
puts "Static pages deleted."
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.