单例在 Rails 请求范围内 [英] Singleton in scope of a request in rails

查看:51
本文介绍了单例在 Rails 请求范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 rails 中的单例 mixin 我可以在 rails 应用程序的范围内创建一个单例类.但我想知道有没有办法在特定请求的范围内创建它?

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 ?

推荐答案

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

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

用法:

def index
  RequestSingleton.instance.do_some_setup

  # ...

  RequestSingleton.clear
end

...以及其他任何地方只需使用 RequestSingleton.instance 即可访问它.

...and anywhere else simply use RequestSingleton.instance to access it.

因为它是线程本地的,所以不存在同步问题.

Since it is thread local, there are no synchronization issues.

这篇关于单例在 Rails 请求范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆