Emmanuel Oga’s Weblog

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

Posteado por: emmanueloga en: 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

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:

# Avoid rails loading this file in every request (in dev mode)
unless Dependencies.load_once_paths.include? __FILE__
Dependencies.load_once_paths << __FILE__
end

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

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

You can also do this in environment.rb:

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

Escribe un comentario

About Me


Professional Software developer, amateur musician. Obsessed with finding the best algorithms for solving the problems nobody has.

My Profile

View Gustavo Emmanuel Oga's profile on LinkedIn

Recomendame

Recommend Me

Stats

  • 22,132 hits

Twitter

LocosXRails Conference