繁体   English   中英

在Rails中,如何在不发出HTTP请求的情况下获取页面的内容?

[英]In Rails how can I get the contents of a page without making an HTTP request?

这可能确实很明显,但是在Rails中,如何在不发出HTTP请求的情况下获取页面的内容?

即我想在同一服务器上的脚本中获取我的rails应用程序生成的任何页面的内容。 这对于HTTP请求来说当然是微不足道的,但是否则如何获取页面的内容呢?

这是我现在正在做的,可以正常工作:

require 'open-uri'

contents = open("http://localhost/path_to_my_page").read # but I really want to get rid of the overhead of the HTTP request

我需要能够从Rails应用程序中的脚本而不是控制器(例如,使用render_to_string)来执行此操作

这是在控制台中获取页面内容的方式。 它可能对您有用:

require 'action_controller/integration'
app = ActionController::Integration::Session.new;
app.get('/path_to_your_page')
puts app.response.body

在您的控制器中,您可以调用render_to_string而不是render并且返回页面而不是将页面发送到浏览器。
两种方法的参数都相同,因此您需要指定需要呈现的控制器和操作。

为什么不直接使用erb? 查看此问题以获取更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM