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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With