0

Although I have declared the FooFactory class as "Singleton", its class variable @@foo gets instantiated every time. Why is this so?

The main singleton class:

require 'singleton'

class FooFactory
  include Singleton
  @@foo = nil

  def get_foo
    print @@foo.nil?.to_s
    @@foo  ||= "I am a string"
    return @@foo
  end
end

The controller code:

class PagesController < ApplicationController
  def home
    @foo = FooFactory.instance.get_foo
  end
end

The view code :

<%= @foo %>

I expect that the print method in the FooFactory should return false after the FooFactory has been instantiated for the first time. But the console keeps on printing true everytime I refresh the pages/home view.

1
  • Have you tried running similar code using ordinary Ruby (ie no Rails, and not including anything you don't need) and seen what you got? Commented Jun 26, 2011 at 23:13

1 Answer 1

6

In development mode, classes are reloaded on every request, losing any class state that you may have stuffed into them. This can be changed by looking for this line in development.rb:

config.cache_classes = false

and changing it to true, which is how it's usually set in production.rb. The reason for setting it to false is convenience: you can edit your code and hit refresh to see the changes without restarting your server.

But in Rails it's not common to put state into classes and expect it to stay between requests, because virtual machines come and go, and threaded VMs may not access the class state in a thread-safe way. There are workarounds for those issues, but usually there's a better way to do whatever you're doing.

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

1 Comment

Thanks.. Could you refer me to some page that explains more about the stuff that you mentioned in the last para.

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.