Search code examples
ruby-on-railsmultithreadingunicorn

Is it safe to use Thread.current with Unicorn in Rails?


I need to get current login user name in model code, but I dont want to add a new additional parameter that will require many changes. So I am thinking whether it works to put the login user name in Thread.current, and then access it in model code. It works in a simple try, but I have a concern whether it can work properly with unicorn multi workers, for example - the login request is handled by worker 1, and the 2nd request is handled by worker 2. My basic understanding is that it should be ok because I set it from session into Thread.current in ApplicationController before filter that should be executed in the beginning of each request. - if a unicorn worker is killed and restarted for whatever reason, is the request will be re-initiated, and still have the session data? I dont have enough knowledge on unicorn... so probably it is a naive question...

And any other possible issue to use Thread.current?

Thanks in advance for your help!


Solution

  • You don't have to use Threads directly, you can use this gem https://github.com/steveklabnik/request_store

    Your User model code can look something like this:

    def self.current_user
      RequestStore.store[:current_user]
    end
    
    def self.current_user=(logged_in_user)
      RequestStore.store[:current_user] = logged_in_user
    end
    

    And in your controller, after login you can set User.current_user = current_user