Are Thread.current[] values and class level attributes safe to use in rails?

馋奶兔 提交于 2019-12-10 21:35:49

问题


I have a particular problem I'm trying to solve in a rails 3 app, and the two common solutions that I'm seeing are these:

Thread.current[:something] = value

and

class Foo
  cattr_accessor :bar
end

Foo.bar = value

Are these methods of data storage (and the corresponding retrieval) safe across multiple users making a request to my rails app, at the same time?

I'm concerned about Thread.current, because a web server could use a single thread to serve up multiple requests, right? Or is there something in the way rails handles threads to prevent problems when using Thread.current? I see Acts As Current uses Thread.current to store the current user, so that gives me hope... but I want authoritative confirmation.

I'm also concerned about class level attributes in a production environment, because I would expect rails to cache class objects in memory, for performance reasons. Does a class level attribute get re-used across requests? or is it safe due to something that rails does to handle class attributes across requests? again, i would like authoritative confirmation of this.

... this app uses Ruby 1.9.2@p180, with Rails 3.0.9


回答1:


Safe enough to store the time zone of the current request:

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/time/zones.rb



来源:https://stackoverflow.com/questions/6659221/are-thread-current-values-and-class-level-attributes-safe-to-use-in-rails

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