Singleton in scope of a request in rails [closed]

时间秒杀一切 提交于 2019-12-06 20:56:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!