Rails: Thread.Current hash for exchanging data with the scope of the request

I plan to use the Thread.Current hash in ruby ​​to exchange information on each request area in the Rails application. (I know that this may not be the best design decision and may even break MVC). I am considering the approach mentioned here http://coderrr.wordpress.com/2008/04/10/lets-stop-polluting-the-threadcurrent-hash/

This basically adds the thread_local_accessor method to the class and provides sweeping when a given thread goes out of scope. Does anyone know if this has any other limitations or any errors that I should be aware of? Or any other alternative to request level hashes that is cleaner?

+3
source share
1 answer

The code you are referencing is not thread safe. It uses the ruby ​​Hash class, which is not thread safe. You can protect access using one of the ruby ​​synchronization primitives, for example. Mutex.

Also, I'm not sure that using a global data structure indexed by a thread id is no better than just using Thread.current.

If you are worried about a key collision, why not choose a unique key, such as a GUID. Based on the example in the link provided:

class ThreadedLibrary
  @@LIBRARY_ID = 'D0052660-60E6-4624-B08E-ECA9200B2949'
  Thread.current[@@LIBRARY_ID] = {}

  def self.some_setting= val
    Thread.current[@@LIBRARY_ID][:some_setting] = val
  end

  def self.some_setting
    Thread.current[@@LIBRARY_ID][:some_setting] ||= :default
  end
end
0
source

All Articles