简体   繁体   中英

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?

ie I want to grab the contents of any page that my rails app generates, in a script on the same server. This is of course trivial with an HTTP request, but how can I get the contents of a page otherwise?

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)

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.
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? See this question for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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