Mauno Vähä
Mauno Vähä

Reputation: 9788

Rails: How to pass parameter to custom before_action class?

I am trying to use separate AuthenticationFilter class which takes user role as a parameter, but I canno't find any examples on how to do that. I tried using search and all I see is calling of methods like this:

before_action -> { some_method :some_value }

Or a custom class (like I have) but without parameter:

before_action AuthenticationFilter

These work, but how would I call AuthenticationFilter and give it a parameter such as :superuser ?

Do note: I wan't to use separate class, is this even possible?

Cheers!

Upvotes: 1

Views: 3687

Answers (2)

Mauno Vähä
Mauno Vähä

Reputation: 9788

Okey, I managed to solve it.

I noticed that rails documentation mentioned *_action to call a method with the same name as * specifies. So, before_action seeks for a method named before in a given class.

Therefore I decided to make a block and call AuthenticationFilter before action directly by giving it the parameter:

before_action { |c| AuthenticationFilter.before(c, :superuser) }

Then I modified my AuthenticationFilter class to be like:

class AuthenticationFilter
  class << self
    def before(controller, role)
      puts "Called AuthenticationFilter with role: #{role}"
    end
  end
end

Hence, also noticed that using typical only and except rules works as well when doing:

before_action only: [:show, :edit] do |c| 
  AuthenticationFilter.before(c, :superuser) 
end

Upvotes: 4

fylooi
fylooi

Reputation: 3870

How about wrapping your class initialization in a method?

before_action :set_authentication_filter

def set_authentication_filter
  # initialize your class here with custom parameters
end

Upvotes: 0

Related Questions