title: Rails: Set a common or global instance variable across several controller actions
body: <p>How should one have several different controller' actions set a common instance variable <strong>for use in templates</strong> but <strong>after the action runs</strong>.</p>
  
  <p>In other words, I want this to work in my application_controller.</p>
  
  <pre><code>class ApplicationController &lt; ActionController::Base
    after_filter :set_something_common
  
    def set_something_common
      # All controllers' actions have queried the DB and set @foo for me...
      @bar = some_calculation_on(@foo)
      # ... and all templates expect @bar to bet set.
    end
  end
  </code></pre>
  
  <p>This <strong>does not work</strong> because <code>after_filter</code> runs after rendering. Fine. But what is the correct pattern?</p>
  
  <p>Again, it is important that <code>set_something_common</code> runs after the action because those actions do case-specific things; but they all set <code>@foo</code>.</p>
  
  <p>None of my ideas seem ideal:</p>
  
  <ul>
  <li>Call <code>set_something_common()</code> towards the bottom of every action that needs it.</li>
  <li><p>Refactor all controllers' case-specific code into <code>case_specific_code()</code> and force them to run in order:</p>
  
  <pre><code>before_filter :case_specific_code, :set_something_common
  </code></pre></li>
  <li><p>Subclass <code>application_controller</code> and redefine the <code>index</code> method.</p></li>
  </ul>
  
  <p>Any thoughts?  Thanks.</p>
  
  <h3>Edit: Matthew's response prompted me to clarify:</h3>
  
  <p>Several controlers' index() all do pagination, each taking parameters <code>@offset</code> and <code>@limit</code> (via a global <code>before_filter</code>) to view data slices. Great. Now I want a common method to compute a RESTful URL for the "next slice" link. I was encouraged to see that <code>url_for()</code> generates a URL returning to the same resource, so I tried:</p>
  
  <pre><code>def set_something_common # really called set_next_url, truth be told
    @next_url = url_for(:offset =&gt; @offset + @limit, :limit =&gt; @limit)
  end
  </code></pre>
  
  <p>I will try monkey patching Fixnum, so I can do something like <code>@offset.next_url_for(self, @limit)</code> from the template, but I'm not sure if it will work.  Come to think of it, if I am going to modify the templates, then I may as well set up an application helper.  I'm still not sure what the best solution is.</p>
  
  <h2>Update: Accepted answer is "use a helper."</h2>
  
  <p>Thanks for the updates from everybody. I learned my lesson that helpers, like global variables, are there for a reason and not to be eschewed when they are plainly beneficial and succinct.</p>