问题
Using singleton mixin from rails I could create a singleton class in the scope of rails app. But I was wondering Is there a way to create it in the scope of a particular request ?
回答1:
Since a request is tied to a thread, you can use Thread local store:
class RequestSingleton
def self.instance
Thread.current['request-singleton'] ||= RequestSingleton.new
end
def self.clear
Thread.current['request-singleton'] = nil
end
end
Usage:
def index
RequestSingleton.instance.do_some_setup
# ...
RequestSingleton.clear
end
...and anywhere else simply use RequestSingleton.instance
to access it.
Since it is thread local, there are no synchronization issues.
来源:https://stackoverflow.com/questions/24927928/singleton-in-scope-of-a-request-in-rails