Old Emmanuel Oga's Weblog (new one is at www.emmanueloga.com)

Delights of autoload in rails (or: Fixing class variables being cleared between requests)

Posted in Uncategorized by emmanueloga on enero 31, 2008

For anyone not familiar with http://dev.rubyonrails.org/ticket/6730, I will tell you a story…. (p.s.: ticket was set to invalid, but explains very well the problem I was having)

I had this beautiful class written in a file on the /lib directory of my rails directory. That class stored some data in class variable. Something like this:

# /lib/nice_class.rb
class NiceClass
mattr_accessor :value
end

# /config/environment.rb
NiceClass.value= “Hi there” # << NiceClass auto-loaded by rails[/sourcecode]Ok what happened is that in first request, the value was right, and if I displayed that value in a view, it showed me the message. On second request, I loosed the message! That was because of rails loading the class in every request. That didn't happened on production mode. Solution: In the class file, I put: [sourcecode language='ruby'] # Avoid rails loading this file in every request (in dev mode) unless Dependencies.load_once_paths.include? __FILE__ Dependencies.load_once_paths << __FILE__ end[/sourcecode]

Tagged with:

2 comentarios

Subscribe to comments with RSS.

  1. Richard said, on noviembre 23, 2008 at 5:04 am

    In development mode, all classes are auto-refreshed. This is design behavior so when you save a file you see the changes reflected immediately.

  2. Casper Fabricius said, on febrero 19, 2009 at 8:34 am

    You can also do this in environment.rb:

    config.to_prepare do
    NiceClass.value= “Hi there”
    end


Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: