Call URLs on your app from the Rails console
Here’s a neat trick I just learned from Obie Fernandez (The Rails Way, p. 30: you can see what your Rails app’s HTML output is from the console. To make this work you have to fool the app into thinking that there’s a request coming in by setting some environmental variables, and then call the dispatcher.
But wouldn’t it be nice to have a single method call, that uses url_for syntax?
class Object
def request(options = {})
method = options.delete(:method) || :get
options.reverse_merge!(:only_path => true)
ENV['REQUEST_URI'] = app.url_for(options)
ENV['REQUEST_METHOD'] = method.to_s
Dispatcher.dispatch
end
end
First we pull the method (:get, :post etc.) out, if it exists. By default we want it to be :get. Then we call url_for and have it only return the path, without any leading domain info. Next we populate the environmental variables and call the dispatcher. The return output will be the HTML your app renders.
To make the trick universally accessible on your development box, put the above code in ~/.irbrc:
Then, fire up the console to your favorite rails app, and call:
>> request(:controller => 'my_controller', :action => 'the_action')
You should see the HTML output scroll by.
Portland and Mt. Hood
