3

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

Derick Bailey
  • 72,004
  • 22
  • 206
  • 219

1 Answers1

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

Will Green
  • 932
  • 5
  • 10
  • 2
    bad example of 'safe' since that's actually a widely-complained about bug in Rails, that setting the timezone only for User1 will change the timezone for User 2 to the same timezone 'sometimes' (when they end up sharing the same thread) – jpw Jan 28 '13 at 18:25