开发者

Render a page as a saved HTML file using Rails 3.0?

开发者 https://www.devze.com 2023-03-16 08:29 出处:网络
I\'m building a simple website generator application in Rails 3.0. I\'d like a \"pu开发者_如何学Goblish\" action in a controller that works just like an ordinary \"show\" action, but instead, saves a

I'm building a simple website generator application in Rails 3.0. I'd like a "pu开发者_如何学Goblish" action in a controller that works just like an ordinary "show" action, but instead, saves a page as an HTML file in the "public" directory instead of displaying it in the browser. That is, I'd like to use the Rails render mechanism to create a file instead of providing an HTTP response.

What's the best way to do this?

Should I simply add caches_page :publish to the controller?

Or use render_to_string and File.new?


You can use render_to_string method: http://apidock.com/rails/AbstractController/Rendering/render_to_string

You still need to respond from the controller though. Maybe redirect to the page you just saved?


I would go with page caching.

Then if you have editable content, the pages should be automatically generated. You could then write a system task which bundles them up as a web site.

see (whatever)/actionpack/lib/action_controller/caching/pages.rb for instructions.


I found that page caching using caches_page won't work for me because there is no way to show a notification or redirect to another page after caching the page. The method render_to_string (suggested by @Grocery) is the way to go. Here's the example controller code:

def publish
  @article = Article.find(params[:id])
  html = render_to_string(:template => "articles/template.html.haml", :layout => 'article' )
  FileUtils.makedirs("#{Rails.root}/public/articles/") unless File.exists?("#{Rails.root}/public/articles/")
  File.open("#{Rails.root}/public/articles/#{@article.filename}.html", 'w') {|f| f.write(html) }
  respond_to do |format|
    format.html # publish.html.erb
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消