saving html from ruby on rails output to a variable
I have a ruby on rails website. The page is dynamically loaded and generated using ruby and rails. However, I'd like to also generate a static .html page to ease my server rather than calling the rails page every time.
In PHP I know how to capture the output buffer using ob_start() and ob_get_contents() to get the outputted text.
How do I capture the output from my rails page into a variable?
EDIT: The reason I want to do this is so that I can save my page as .htm开发者_如何学JAVAl for use on other machines. So I generate the HTML using ruby and distribute to others in a format they can view.
You should use Rails caching to achieve this result. It achieves the ends you are looking for.
Alternatively, you can render_to_string and output the result using render:
#ticket_controller.rb
def TicketController < ApplicationController
def show_ticket
@ticket = Ticket.find(params[:id])
res = render_to_string :action => :show_ticket
#... cache result-- you may want to adjust this path based on your needs
#This is similar to what Rails caching does
#Finally, you should note that most Rails servers serve files from
# the /public directory without ever invoking Rails proper
File.open("#{RAILS_ROOT}/public/#{params[:action]}.html", 'w') {|f| f.write(res) }
# or .. File.open("#{RAILS_ROOT}/public/#{params[:controller]}/#{params[:action]}/#{params[:id]}.html", 'w') {|f| f.write(res) }
# or .. File.open("#{RAILS_ROOT}/snapshots/#{params[:controller]}/#{params[:action]}/#{params[:id]}.html", 'w') {|f| f.write(res) }
render :text => res
end
end
You probably want to look into caching rather then saving the output of your rails app directly. Check out:
- http://guides.rubyonrails.org/caching_with_rails.html
- http://api.rubyonrails.org/classes/ActionController/Caching/Pages.html
I ended up going with the following:
@page_data = render_to_string() # read the entire page's output to string
if (File.exist?('../cache.html'))
file = File.open('../cache.html','rb')
contents = file.read
else
contents = ''
end
if (@page_data!=contents) # if the page has changed
# save the output to an html version of the page
File.open('../cache.html','w') {|f| f.write(@page_data) }
end
精彩评论