How to set in a middleware a variable accessible in all my application?

前端 未结 4 1881
栀梦
栀梦 2021-02-13 21:39

I am using Ruby on Rails 3 and I am trying to use middlewares in order to set a variable @variable_name accessible later in controllers.

For example my midd

相关标签:
4条回答
  • 2021-02-13 22:30

    You can have a cattr_accessor :my_var in any model and set this variable from middleware by

      MyModel.my_var = 'something'
    

    And you can access this anywhere in the application.

    0 讨论(0)
  • 2021-02-13 22:32

    I don't know if this can be done with a Middelware. My suggestion would be this:

    class ApplicationController < ActionController::Base
    
      protect_from_forgery
    
      before_filter :set_my_var
    
    private
      def set_my_var
        @account ||= Account.find(1)
      end
    
    end
    

    This way all your controllers and views have access to @account

    0 讨论(0)
  • 2021-02-13 22:41

    You can use 'env' for that. So in your middleware you do this:

    def call(env)
      env['account'] = Account.find(1)
      @app.call(env)
    end
    

    You can get the value by using 'request' in your app:

    request.env['account']
    

    And please don't use global variables or class attributes as some people suggest here. That's a sure way to get yourself into troubles and really is a bad habit.

    0 讨论(0)
  • 2021-02-13 22:43

    Have you tried creating a Ruby global variable?

    def call(env)
      $account ||= Account.find(1)
    
      @app.call(env)
    end
    

    and

    <%= debug $account %>
    
    0 讨论(0)
提交回复
热议问题