Ruby class variable is reset after rails app initialized

Posted by Phuong Nguy?n on Stack Overflow See other posts from Stack Overflow or by Phuong Nguy?n
Published on 2010-06-15T04:08:16Z Indexed on 2010/06/15 4:12 UTC
Read the original article Hit count: 227

Filed under:

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails