How can I send a parameter to a before filter?

后端 未结 5 1977
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 10:55

I\'d like to create a before_filter method in my application controller like this...

def check_role(role_name)
  unless logged_in_user.has_role? role_name
    fl         


        
5条回答
  •  清酒与你
    2021-02-08 11:22

    You can use a bit of meta-programming. Something like this (completely untested, just something to give you an idea of how it might go):

    Module RoleWithIt
      Role.all.each do |role|
        define_method("check_#{role.name}_role".to_sym) do
          check_role(role.name)
        end
      end
    
      def check_role(role_name)
        return if logged_in_user.has_role?(role_name)
        flash[:notice] = 'Access to that area requires additional privileges.'
        redirect_to :back
      end
    end
    
    ApplicationController.send :include, RoleWithIt
    

    To have it load when your app initialises, just put it in a file called role_with_it.rb and put it in your lib directory.

提交回复
热议问题