title: Singleton in Rails
body: <p>I'm creating a simple Rails 5 app. The goal of the app is to use a statistical model to do simple predictions and display them.</p>
  
  <p>I have a <code>Statistics</code> class (Plain Ruby class) that holds a neural network as an instance @attribute to make my predictions.</p>
  
  <p>There should only be one instance of the <code>Statistics</code> class, so I used the <code>singleton</code> mixin:</p>
  
  <pre><code>require 'singleton'
  
  class Statistics
    include Singleton
  
    def initialize
      @neuralnet = NeuralNet.new
    end
  
    def make_prediction(input)
      @neuralnet.make_prediction(input)
    end
  
    def train_model(data)
      @neuralnet.train(data)
    end
  
    ...
  
  end
  </code></pre>
  
  <p>And from <code>config/initializers/Statistics.rb</code> my intention is to initialize the neural network when the app initializes itself, since the model needs to be trained with data to make predictions. I call the Statistics singleton instance from there.</p>
  
  <pre><code># CSV reading and data importing to obtain training_data
  
  Statistics.instance.train_model(training_data)
  </code></pre>
  
  <p>And then I try to use the trained instance from a controller, like so:</p>
  
  <pre><code>@prediction = Statistics.instance.make_prediction(input)
  </code></pre>
  
  <p>The prediction is good the first time the app loads the page. If I try to make another prediction, it fails miserably. I printed the <code>object_id</code> and discovered the <code>@neuralnet</code> ID changes after every page load, so basically my understanding is that the singleton is not working and I'm getting a fresh new, untrained model every time I try to make a new prediction.</p>
  
  <p>It's really frustrating. Please help me out, I don't know if my understanding of the Singleton behavior is correct or if I should be using singletons at all. I just need a single instance of my trained neural net and call it from my controller... how can I accomplish that?</p>