Execute Rails Code Before the View is Rendered

At one time, I was looking for a way to execute code for every action in my controller before the view was rendered. I saw this come up again yesterday in the #rubyonrails IRC channel so I looked at it a bit more. Currently, Rails provides a before_filter method which will “run before actions on this controller are performed” or an after_filter which will “run after actions on this controller are performed.” What I wanted was a before_render filter which would run right at the end of the action but before render/view was executed.

Here is one idea how to do this. Since you want the code to run right before render is executed just override the render method that’s in ActionController. You can put the following code inside any of your individual controllers or add it to your ApplicationController and it will run in all of your controllers.

protected
  def render(options = nil, deprecated_status = nil, &block)
    # your code goes here
    @rockon = "rock and roll!"

    # call the ActionController::Base render to show the page
    super
  end

This is just an example, and maybe someone will take this a step further and actually create a before_render filter plugin. It would be nice to have the same flexibility as before_filter and after_filter which allows you to include “:only” or “:exclude” certain actions.

6 Responses

  1. I was Googling in search for a solution to the exact same problem. I have crammed quite a bit of application logic into my custom render() and was looking for a way to move it somewhere where it belongs, and here you are, telling me that indeed there’s no place like render(). :)

  2. Thx for this first solution. I think Rails should hurry up to implement a before_render filter. Thats definately a often needed requirement.

  3. You’re welcome Christian. Glad it helped.

  4. I completely agree. A before_render filter would be sweet.