Nat*_*ugh 3 ruby-on-rails ruby-on-rails-3
我在rails网站上有一个ruby.使用ruby和rails动态加载和生成页面.但是,我还想生成一个静态.html页面来简化我的服务器,而不是每次调用rails页面.
在PHP中,我知道如何使用ob_start()和ob_get_contents()来获取输出缓冲区以获取输出文本.
如何将rails页面的输出捕获到变量中?
编辑:我想这样做的原因是我可以将我的页面保存为.html,以便在其他机器上使用.所以我使用ruby生成HTML并以他们可以查看的格式分发给其他人.
您应该使用Rails缓存来实现此结果.它实现了您正在寻找的目标.
或者,您可以使用render渲染render_to_string并输出结果:
#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
Run Code Online (Sandbox Code Playgroud)