如何将 ActiveSupport::Concern 应用于控制器中的特定操作?

Eki*_*bal 6 ruby ruby-grape activesupport-concern

我正在使用 Grape 构建 API。

我创建了一个ActiveSupport::Concern让我们说的名字Authentication,我在过滤器之前应用了一些,所以我的担忧看起来像:

module Authentication
  extend ActiveSupport::Concern

  included do
    before do
      error!('401 Unauthorized', 401) unless authenticated?
    end
    ....
  end
end
Run Code Online (Sandbox Code Playgroud)

现在让我们说在我的 UserController 中,我只想将这个问题应用于特定的操作。我怎样才能做到这一点?

  class SocialMessagesController < Grape::API
    include Authentication

    get '/action_one' do
    end

    get '/action_two' do
    end

  end
Run Code Online (Sandbox Code Playgroud)

任何简单的方法来指定特定方法的关注点,就像before_filter在带有only选项的rails 中一样?

ano*_*rmh 0

将您的操作分成不同的类,然后将它们安装在包装类中:

class SocialMessagesOne < Grape::API
  include Authentication

  get '/action_one' do
    # Subject to the Authentication concern
  end
end
Run Code Online (Sandbox Code Playgroud)
class SocialMessagesTwo < Grape::API
  get '/action_two' do
    # Not subject to the Authentication concern
  end
end
Run Code Online (Sandbox Code Playgroud)
class SocialMessagesController < Grape::API
  mount SocialMessagesOne
  mount SocialMessagesTwo
end
Run Code Online (Sandbox Code Playgroud)

有关安装的更多信息,请参阅Grape 自述文件