0

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)

DanSingerman
  • 36,066
  • 13
  • 81
  • 92

3 Answers3

3

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
  • 9,719
  • 2
  • 37
  • 41
  • 2
    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 Jan 11 '10 at 18:46
  • Ok, I'll have to look more closely at this, thanks for your patience. – DanSingerman Jan 12 '10 at 08:22
  • 1
    Hmm...I am using Rails 2.3.4 and my second app.get throws a "ThreadError: stopping only thread" error. Any ideas? – DanSingerman Jan 12 '10 at 12:00
  • 1
    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 Jan 12 '10 at 19:26
  • 1
    Ok, got this working by manually applying the patch at your link. – DanSingerman Jan 13 '10 at 12:16
1

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
  • 37,240
  • 11
  • 105
  • 116
  • Thanks, but I need to do it from a separate script, not from within the controller. – DanSingerman Jan 11 '10 at 14:10
  • 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 Jan 11 '10 at 15:31
  • Yeah, but my controller already does that; I don't want to re-invent what I already have – DanSingerman Jan 11 '10 at 16:03
0

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

Community
  • 1
  • 1
Jeff Paquette
  • 7,089
  • 2
  • 31
  • 40