简体   繁体   English

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

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

This may be really obvious, but in rails how can I get the contents of a page without making an HTTP request? 这可能确实很明显,但是在Rails中,如何在不发出HTTP请求的情况下获取页面的内容?

ie I want to grab the contents of any page that my rails app generates, in a script on the same server. 即我想在同一服务器上的脚本中获取我的rails应用程序生成的任何页面的内容。 This is of course trivial with an HTTP request, but how can I get the contents of a page otherwise? 这对于HTTP请求来说当然是微不足道的,但是否则如何获取页面的内容呢?

This is what I am doing now which works fine: 这是我现在正在做的,可以正常工作:

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

I need to be able to do this from a script, within the rails app, not a controller (eg with render_to_string) 我需要能够从Rails应用程序中的脚本而不是控制器(例如,使用render_to_string)来执行此操作

This is how you get the contents of a page in the console. 这是在控制台中获取页面内容的方式。 It might work for you: 它可能对您有用:

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

In your controller , you can call render_to_string instead of render and the page is returned instead of being send to the browser. 在您的控制器中,您可以调用render_to_string而不是render并且返回页面而不是将页面发送到浏览器。
The arguments of both methods are the same, so you need to specify which controller and action you require to render. 两种方法的参数都相同,因此您需要指定需要呈现的控制器和操作。

Why not use erb directly? 为什么不直接使用erb? See this question for more details 查看此问题以获取更多详细信息

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

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