Skip to content

Instantly share code, notes, and snippets.

@chuckbjones
Created August 22, 2012 07:51
Show Gist options
  • Save chuckbjones/3423566 to your computer and use it in GitHub Desktop.
Save chuckbjones/3423566 to your computer and use it in GitHub Desktop.
Generate static html files at deploy time in Rails 3.x
# define a method to run rake tasks
def run_rake(task, options={}, &block)
rake = fetch(:rake, 'rake')
rails_env = fetch(:rails_env, 'production')
command = "cd #{current_path} && #{rake} #{task} RAILS_ENV=#{rails_env}"
run(command, options, &block)
end
# generate static html files
after "deploy:create_symlink", "static:generate"
namespace :static do
desc "Generate static html files and put them in /public/"
task :generate do
run_rake 'static:generate'
end
end
# adapted from http://kill-0.com/duplo/2010/01/29/a-different-take-on-custom-error-pages-in-ruby-on-rails/
namespace :static do
desc "Generate static pages and save them in /public"
task :generate => :environment do
require "rails/console/app"
require "rails/console/helpers"
extend Rails::ConsoleMethods
urls_and_paths.each do |url, path|
r = app.get(url)
if 200 == r
File.open(Rails.public_path + path, "w") do |f|
f.write(app.response.body)
end
else
$stderr.puts "Error generating static file #{path} #{r.inspect}"
end
end
end
end
private
def urls_and_paths
Dir.glob("#{Rails.root}/app/views/static/*.html.erb").map do |file|
file = File.basename(file, '.html.erb')
["/static/#{file}", "/#{file}.html"]
end
end
@justqyx
Copy link

justqyx commented Apr 22, 2013

我认为,这里要这样写

if 200 == r
  File.open(Rails.public_path + path, "w:UTF-8") do |f|
    f.write(app.response.body.force_encoding("UTF-8"))
  end
else
   $stderr.puts "Error generating static file #{path} #{r.inspect}"
end

@jarthod
Copy link

jarthod commented Feb 7, 2021

For the record since Rails 5 it's slightly simpler to render a page from anywhere (like rake task) with:

html = ApplicationController.render(template: "static/page.html.erb", layout: "layouts/static")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment