views:

98

answers:

3

This may be really obvious, but in rails how can I get the contents of a page without making an HTTP request?

i.e. 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 (e.g. with render_to_string)

+1  A: 

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.

Veger
Thanks, but I need to do it from a separate script, not from within the controller.
DanSingerman
From a script you can use erb directly (as suggested in the answer of flyfish64), but you need to initialize all variables you use in your view manually, since you are not using your controller to fill in the variables.
Veger
Yeah, but my controller already does that; I don't want to re-invent what I already have
DanSingerman
A: 

Why not use erb directly? See this question for more details

Jeff Paquette
+3  A: 

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
mckeed
app.get does an HTTP request
DanSingerman
It simulates an http request in order to set up all the environment your controller needs. It doesn't actually make a request to your server from "outside" like your version does. For example, it will still work if your server isn't running.
mckeed
Ok, I'll have to look more closely at this, thanks for your patience.
DanSingerman
Hmm...I am using Rails 2.3.4 and my second app.get throws a "ThreadError: stopping only thread" error. Any ideas?
DanSingerman
Hm, yes. It appears that you won't be able to do it this way until this bug is fixed:http://rails.lighthouseapp.com/projects/8994/tickets/3153
mckeed
Ok, got this working by manually applying the patch at your link.
DanSingerman