Search code examples
ruby-on-railsruby-on-rails-4before-filter

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!


Solution

  • 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