# ActiveRecord models stored in globals lose methods

**URL:** <https://www.ruby-forum.com/t/activerecord-models-stored-in-globals-lose-methods/134625>\
**Category:** Rails\
**Created:** [April 13, 2008, 3:20am UTC](https://www.ruby-forum.com/t/activerecord-models-stored-in-globals-lose-methods/134625 "2008-04-13T03:20:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dukael](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c77e96/32.png) [@dukael](https://www.ruby-forum.com/u/dukael)\
**Post date:** [April 13, 2008, 3:20am UTC](https://www.ruby-forum.com/t/activerecord-models-stored-in-globals-lose-methods/134625/1 "2008-04-13T03:20:29Z")

</div>

Hi all,

I was experimenting with storing models in Ruby’s global space (as a  
quick and dirty alternative to memcached), and I came across some  
weird behavior I couldn’t figure out.

First, I create a basic ActiveRecord model:

class Bob \< ActiveRecord::Base  
def chunky; ‘bacon’; end  
end

Next, I write a controller that sticks the model in a global and calls  
a method:

class TestController \< ApplicationController  
def index  
$some\_global ||= Bob.new  
render :inline =\> $some\_global.chunky  
end  
end

Then I start up a Mongrel via script/server and call the  
TestController. The first time I do this, things go as expected: it  
just spits out ‘bacon’. The second time, however, I get a  
NoMethodError saying $some\_global doesn’t have a chunky method. I  
checked $some\_global’s class and depending on the method called, get  
weird results:

$some\_global.class # =\> Bob  
$some\_global.is\_a? Bob # =\> false

I also ran $some\_global.methods, which prints out of the methods  
associated with ActiveRecord (e.g. save and valid?) but no chunky.

This only appears to happen with models inheriting from ActiveRecord.  
Removing ActiveRecord::Base from the inheritance chain seems to avoid  
this problem.

Anyone have any ideas why this happens? Thanks!

– Andrew

---

<div class="post-metadata">

**Author:** ![dukael](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c77e96/32.png) [@dukael](https://www.ruby-forum.com/u/dukael)\
**Post date:** [April 13, 2008, 12:54pm UTC](https://www.ruby-forum.com/t/activerecord-models-stored-in-globals-lose-methods/134625/2 "2008-04-13T12:54:34Z")

</div>

On 13 Apr 2008, at 02:20, Andrew F. wrote:

> I also ran $some\_global.methods, which prints out of the methods  
> associated with ActiveRecord (e.g. save and valid?) but no chunky.
> 
> This only appears to happen with models inheriting from ActiveRecord.  
> Removing ActiveRecord::Base from the inheritance chain seems to avoid  
> this problem.

In development mode classes are reloaded on each request. The nitty  
gritty of how this is implemented essentially involves dismantelling  
your models and throwing them away. If you hang onto a class via a  
global variable or similar then you get the thrown away version of the  
class.

Fred
