简体   繁体   中英

How can I make session data available to my ruby gem in a thread safe way?

I have a API gem which is a public helper library that uses faraday to make resourceful requests to my API. I would like to make a middleware that checks if session data is present (in the form of a hash) and if so would merge these values into the arguments of any request that faraday makes.

My initial attempt involved setting a metaclass attr_accessor (global_params) in the gem's top level class (ie MyGem.global_params). The middleware could check this variable for necessary data. This meant that any ApplicationController that had access to my library could implement a before_filter that would set the global_params based on session data and an after_filter could clear it.. so that all faraday requests made by that instance of ApplicationController would share the same global_params set form the session data.

I now wonder if this is thread safe.. and if not what another way I could handle this is?

As for your other question, globals are almost always a sign of doing it wrong and should be avoided whenever possible.

What you need here is a factory method that can customize your context as required.

For example, you're probably doing something like this:

MyGem.global_arg = :foo
MyGem.new(...)

What you could do instead is this:

factory = MyGem.factory(:global_arg => :foo)

factory.new(...)

Or, to preserve a similar sort of feel:

factory = MyGem.factory do |factory|
  factory.global_arg = :foo
end

Instead of creating a mattr_accessor in MyGem, you'd create one as an independent object of which MyGem could have a default instance of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM