在Rails中,请求范围内的单例模式

10

使用Rails中的singleton mixin,我可以在Rails应用程序的作用域中创建一个单例类。但我想知道是否有一种方法可以在特定请求的范围内创建它。

1个回答

9

由于请求与线程相关,因此您可以使用Thread local存储:

class RequestSingleton
  def self.instance
    Thread.current['request-singleton'] ||= RequestSingleton.new
  end

  def self.clear
    Thread.current['request-singleton'] = nil
  end
end

使用方法:

def index
  RequestSingleton.instance.do_some_setup

  # ...

  RequestSingleton.clear
end

在任何地方,只需使用RequestSingleton.instance来访问它。

由于它是线程本地的,所以不存在同步问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接