Why are my thread variables intermittent in Rails?

前端 未结 1 1277
生来不讨喜
生来不讨喜 2021-02-11 09:45

I have the following in my application controller:

before_filter :set_current_subdomain

  protected
    def set_current_subdomain
      Thread.current[:current_         


        
相关标签:
1条回答
  • 2021-02-11 10:17

    Manipulating the Thread local variables is a really bad idea and is going to lead to nothing but sadness, heartache, and pain. There's no guarantee that different parts of the request processing will be handled by the same thread, and because of this, your variables might end up getting lost.

    The Rails convention is to create instance variables in the context of ApplicationController. In simple terms, all you really do is this:

    class ApplicationController < ActionController::Base
      before_filter :set_current_subdomain
    
      attr_reader :current_subdomain
      helper_method :current_subdomain
    
    protected
      def set_current_subdomain
        @current_subdomain = request.subdomain
    
        @account = Account.find_by_subdomain(@current_subdomain)
      end
    end
    

    Any @... type variables you create will be attached to the instance of the ApplicationController associated with the current request. It's important to note that each request will be issued a brand-new instance of the appropriate controller class.

    You're free to create whatever instance variables you want provided they don't somehow conflict with those used by Rails itself but in general terms this doesn't happen very often and conflicts typically occur on method names instead.

    Class-level instance variables will persist between requests in environments where the "cache classes" flag is enabled. In the development environment your controller class is re-loaded each time a request is made to ensure it reflects the current state of your source files.

    0 讨论(0)
提交回复
热议问题