title: In Ruby on Rails how can I persist objects in memory between sessions
body: <p>I'm trying to build something (ultimately a gem but for now an application) that works as follows.</p>
  
  <p>Suppose for example the DB records are breeds of dog.  There's a Dog parent class and a child class for each breed.  The actual breeds aren't known until runtime.</p>
  
  <p>When the server begins it will load up records from the DB and instantiate instances of classes based on the records, e.g. I may have two beagles and poodle.  When someone comes to the server they may want to access one of those dog instances.</p>
  
  <p>Why not just create the instance on the fly?  In my case the "dogs" are basically classes that hold an algorithm and data.  The algorithm doesn't change, the data changes rarely (on the order of days), but the execution of the algorithm itself, which uses both data and some dynamic data passed in such as a timestamp, will be accessed multiple times a second.</p>
  
  <p>It would be silly to have to recreate an instance of the object and load the data each time just to do a request only to do it again on the next request (the requests don't change the state of the object).  I'd be creating and destroying multiple objects a second when I could just reuse the same object.</p>
  
  <p>it doesn't make sense to keep it in the session, since someone wanting a poodle shouldn't need to have the beagles information in her session object; it's irrelevant (and doesn't scale).</p>
  
  <p>How do I persist these objects in memory?  I basically want a lookup table to hold the instances.  In Java I would create a singleton with some type of hashmap or array that sits in memory.  In rails I tried this by creating a singleton class in the lib folder.  I think--I may not be understanding this right--that the instance (the fact that it's a singleton is moot) is being lost when the session disappears.</p>
  
  <p>The closest answer I found was <a href="http://www.ruby-forum.com/topic/129372" rel="noreferrer">http://www.ruby-forum.com/topic/129372</a> which basically puts everything in class fields and methods.  Somehow that doesn't seem right.</p>
  
  <p>TIA!</p>
  
  <p>Addition: I come from Java.  In Java I'd just create an object that sits on the heap or maybe in a JNDI tree and as HTTP requests came in they'd be handled by a a servlet or EJB or some per-request item which could then access the persistent object.  I can't seem to find the equivalent in rails.</p>