How to apply ActiveSupport::Concern to specific actions in my controller?
Asked Answered
B

1

6

I'm using Grape to build an API.

I created an ActiveSupport::Concern let's say with the name Authentication and I applied some before filter so my concern looks like:

module Authentication
  extend ActiveSupport::Concern

  included do
    before do
      error!('401 Unauthorized', 401) unless authenticated?
    end
    ....
  end
end

Now let's say in my UserController I want to apply this concern only for a specific action. How can I do that?

  class SocialMessagesController < Grape::API
    include Authentication

    get '/action_one' do
    end

    get '/action_two' do
    end

  end

Any easy way to specify the concern for a specific method just like before_filter in rails with only option?

Bul answered 29/9, 2015 at 15:45 Comment(0)
B
0

Separate your actions into different classes and then mount them within a wrapper class:

class SocialMessagesOne < Grape::API
  include Authentication

  get '/action_one' do
    # Subject to the Authentication concern
  end
end
class SocialMessagesTwo < Grape::API
  get '/action_two' do
    # Not subject to the Authentication concern
  end
end
class SocialMessagesController < Grape::API
  mount SocialMessagesOne
  mount SocialMessagesTwo
end

More information on mounting is available in the Grape README.

Breakneck answered 11/7, 2022 at 23:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.