Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Created October 10, 2012 21:56
Show Gist options
  • Save ndbroadbent/3868731 to your computer and use it in GitHub Desktop.
Save ndbroadbent/3868731 to your computer and use it in GitHub Desktop.
Rake task to precompile static pages in app/views/static/ folder
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment