title: Rails Memoization of Helper method
body: <p>I have a helper method that does expensive calculations and returns a <code>Hash</code>, and this Hash is constant during my entire application lifespan (meaning it can only change after a re-deploy) and it also doesn't take any arguments. </p>
  
  <p>For performance, I wish I could 'cache' the resulting <code>Hash</code>.</p>
  
  <p>I <strong>don't</strong> want to use Rails cache for this, since I want to avoid the extra trip to memcached and I don't want the overhead of de-serializing the string into a hash.</p>
  
  <p>My first idea was to assign the resulting hash to a Constant and calling <code>.freeze</code> on it. But the helper is an instance method, the constant lives on the class, and I had to do this ultra hacky solution:</p>
  
  <pre><code>module FooHelper
  
  def expensive_calculation_method
    resulting_hash
  end
  
  EXPENSIVE_CALCULATION_CONSTANT = Class.new.extend(self).expensive_calculation_method.freeze
  </code></pre>
  
  <p>This is due to the helper method being an instance method, the helper being a Module (which leads to the fake Class extend so I can call the instance method) and I also must declare the constant AFTER the instance method (if I declare it right after <code>module FooHelper</code>, I get an <code>undefined method 'expensive_calculation_method'</code>.</p>
  
  <p>The second idea was to use memoization, but at least for Rails Controllers memoization is the persistance of a variable over the lifecycle of a <em>single request</em>, so it's only valuable if you reuse a variable many times from within a <strong>single request</strong>, which is not my case, but at the same time Helpers are modules, not Classes to be instanciated, and by this point I don't know what to do. </p>
  
  <p>How would I cache that Hash, or memoize it in a way that persists over requests?</p>