2

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.