Created
August 22, 2012 07:51
-
-
Save chuckbjones/3423566 to your computer and use it in GitHub Desktop.
Generate static html files at deploy time in Rails 3.x
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
# 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 |
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
# 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 |
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
我认为,这里要这样写