title: What is a good way to memoize data across many instances of a class in Ruby?
body: <p>Consider: many instances of an object that generates data. It would be great to only generate that data once per run.</p>
  
  <pre><code>class HighOfNPeriods &lt; Indicator
    def generate_data
      @indicator_data = DataStream.new
      (0..@source_data.data.count - 1).each do |i|
        if i &lt; @params[:n_days]
        ...
        @indicator_data.add one_data
      end
    end
  </code></pre>
  
  <p>There are different instances of <code>HighOfNPeriods</code> with different <code>params</code> and different <code>@source_data</code>.</p>
  
  <p>Here is how the indicator is used:</p>
  
  <pre><code>class Strategy
    attr_accessor :indicators
  
    def initialize params
      ...
    end
  </code></pre>
  
  <p>The method <code>HighOfNPeriods.generate_data</code> is called from within <code>Strategy</code>. Each <code>Strategy</code> gets a new instance of <code>HighOfNPeriods</code>, so it's not possible to pull it out as some kind of global value. Besides that, it should not be global.</p>
  
  <p><code>unless @indicator_data</code> wouldn't work because the data needs to be shared across many instances of <code>HighOfNPeriods</code>.</p>
  
  <p>So, the question is: </p>
  
  <pre><code>What is a good way to memoize the instance variable `indicator_data` 
  or the object `HighOfNPeriods` when there are many different instances, 
  some of which have different data?
  </code></pre>
  
  <p>One solution is to store the data using ActiveRecord, but that's not really the way I want to do it at this time because:</p>
  
  <ol>
  <li>Not all the generated data can be generated in advance because there are 
     too many permutations of params. It makes more sense to see if it has
     been generated before and then generate (and save) as necessary.</li>
  <li>It doesn't take long to generate the data. It may be generated once and used 
     hundreds of times each run.</li>
  <li>It will be faster to access the data from within the object than to pull it from the database.</li>
  </ol>
  
  <p>Ruby 1.9.3</p>