ActiveRecord models stored in globals lose methods

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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs