views:

42

answers:

1

I tried to assign a class static variable like this

class QueryLogger < Logger
  @@query_logger_default_instance = nil
  def self.default_instance
    # Use global variable because static variable doesn't work
    @@query_logger_default_instance ||= self.new(STDOUT)
  end
end

In initializers folder of my rails app, I added a file with this code block

ActiveRecord::Base.logger = QueryLogger.default_instance

In a request (action of controller), I make a call to this: QueryLogger.default_instance.

My assumption is that the call to default_instance will always report the same. However, it does not.

Now I try to watch stuff in NetBeans by setting breakpoint inside default_instance. Thing happen as expected, the default_instance get called twice, one due to the initializer block and one due to the call to my action. Surprising thing is, in both times, @@query_logger_default_instance report nil inside NetBeans inspector. The first nil report is correct, but the second shocked me. It's look like static variable gets reset after rails app initialized. Is there some magic there?

+2  A: 

It depends if you are running in development environment, classes are loaded per request basis, thats the reason you can make changes to them and see them without restarting the server.

So i think your class variable will be reset for each request.

Try running in production.

Rishav Rastogi
It does make some senses. However, if the class is reloaded, then what about the created instance? Such instance will have no class?
Phương Nguyễn
instances are also created per request basis. So I think Garbage collector takes care of them.
Rishav Rastogi
I created the instances inside an initializer. And it's obvious to me that my initializer is not called twice?
Phương Nguyễn