Ruby on Rails – Internal redirect and render of action from another controller

You probably need to render action from other controller than the one currently processing user’s request and you don’t want to redirect user’s browser. Just in case, make sure you know why you want it :)

I need it because I want to render my 404 and 500 error pages (which I handle throught routes) but I don’t want to raise exception that will be handled so far in ShowExceptions middleware which makes notification in Airbrake which has middleware just bellow it.

So my solution is to create simple middleware placed just above my application which will play request/response ping pong with it as long as the application want to redirect somewhere else. To make this condition I used headers list returned from application to middleware on top of it. When application return respond with X-Internal-Redirect-To header, my middleware throws the request back to the application just with changed PATH_INFO environment variable.

Code

Here is implementation of middleware class. Save it somewhere to your lib folder, eg lib/internal_redirect.rb

Then add it to middleware stack of your application. To do that change your config/application.rb file:

Add require for create class file at the top of application.rb file:

And add ocnfiguration directive

After that, try run “rake middleware” command. “use InternalRedirect” should show up just above the application.

Use it

To use internal redirect, just use “head” method of Action Controller in your actions:

That’s it. Enjoy :)