Ruby on Rails - Access controller variable from model

后端 未结 5 998
深忆病人
深忆病人 2020-11-30 06:12

I am trying to access an instance variable which is set in the controller in the model. The controller is the products controller and the model is the products model. The in

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 06:22

    DISCLAIMER: The following code breaks MVC conventions, that said...

    Using class attributes can probably lead to thread safety issues. I would use Thread.current + around_filter to store controller related data at thread level, and ensure it gets cleared just before the request finishes:

    class ApplicationController < ActionController::Base
    
      around_filter :wrap_with_hack
    
      def wrap_with_hack
        # We could do this (greener solution): 
        # http://coderrr.wordpress.com/2008/04/10/lets-stop-polluting-the-threadcurrent-hash/
        # ... but for simplicity sake:
        Thread.current[:controller] = self
        begin
          yield
        ensure
         # Prevent cross request access if thread is reused later
         Thread.current[:controller] = nil
        end
      end
    end
    

    Now the current controller instance will be avaliable globaly during the request processing through Thread.current[:controller]

提交回复
热议问题