Implementing a Singleton pattern in Ruby
Although I have declared the FooF开发者_运维问答actory 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.
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.
精彩评论