Foliosus Web Design LLC: Your website done right

Blogfolio

Call URLs on your app from the Rails console

Feb 06 ’08

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.

Conversation in progress…

  1. 1

    On May 18th karatedog said:

    It seems that it doesn't work in Rails 2.3.2, nor does what Obie Fernandez suggests in that book.

  2. 2

    On July 29th Greg Moreno said:

    I also had issue running Obie's example in console. I get this error message:

    >> Dispatcher.dispatch
    NoMethodError: undefined method `env_table' for nil:NilClass

  3. 3

    On January 14th Max said:

    Just came here via a Google search to find the solution to the non-working example in The Rails Way. Neither work for me.

    There's a Lighthouse ticket open, but it's been open almost a year now...

    https://awprorubyseries.lighthouseapp.com/projects/6454/tickets/161-dispatcherdispatch-does-not-work-p-30-for-rails-232

Join the conversation

* indicates a required field

New comment

Will never be disclosed or used inappropriately

Enter the word how to confirm that you are a human being

About the author

Brent Miller is the owner and principal web designer of Foliosus Web Design LLC in Portland, Oregon. He enjoys food, plants, and the color green. If you are interested in hiring him for web work, please contact him.

Categories

Plant of the day

Unknown sp. (Bromeliaceae)

Unknown sp. (Bromeliaceae)

Fresh photos