Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .html for use on other machines. So I generate the HTML using ruby and distribute to others in a format they can view.

like image 781
Nate Radebaugh Avatar asked Feb 06 '26 00:02

Nate Radebaugh


1 Answers

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
like image 148
ghayes Avatar answered Feb 08 '26 13:02

ghayes