访问ClassMethod中定义的实例变量

时间:2017-05-17 09:48:41

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个控制器,我想定义一个特定的权限列表,如下所示:

class Backoffice::OrdersController < ApiController
  include BackofficeAuthenticator
  before_action :authenticate_agent
  permissions :admin, :tech_god

我在permission上创建了此方法BackofficeAuthenticator

module BackofficeAuthenticator
  extend ActiveSupport::Concern

  module ClassMethods
    def permissions(*permissions)
      instance_variable_set(:@permissions, permissions)
    end
  end

def authenticate_agent
    raise MissingAccessToken if token.blank?
    @decoded_payload = JWT.decode(token, JWT_SECRET, true, algorithm: 'HS256').first
    if instance_variable_get(:@permissions).present?
      raise NotAllowed if @permissions.include? agent_permissions
    end
  end

但是当我尝试按上述方式阅读此变量时(instance_variable_get(:@permissions).present?),我得到nil。 我的问题是:如何根据需要在控制器上定义权限并在身份验证器模块上访问这些值?

修改

有点得到它,如下:

module ClassMethods
  def permissions(*permissions)
    instance_variable_set(:@defined_permissions, permissions)
  end
end

def authenticate_agent
    raise MissingAccessToken if token.blank?
    @decoded_payload = JWT.decode(token, JWT_SECRET, true, algorithm: 'HS256').first
    defined_permissions = self.class.instance_variable_get(:@defined_permissions)

此时,defined_permissions具有之前设置的值,但我不确定这样做是否正确。

我还在base.extend ClassMethods

的末尾添加了included do |base|

1 个答案:

答案 0 :(得分:1)

module BackofficeAuthenticator
  module ClassMethods
    def permissions=(*permissions)
      @permissions = permissions
    end
    def permissions
      @permissions || [] 
    end
  end

  def self.included base
    base.extend ClassMethods
  end

  def authenticate_agent
    raise NotAllowed if self.class.permissions.include?(agent_permissions)
  end
end