How to pass a parameter to a "before_filter" filter?


I'm very new to rails, so I apologize if my question sounds dumb..

I'm setting up an authentication system for this project. In order to
login someone has to feed username/password. Since there are several
portions of the project to be password protected I sticked
"check_authentication" under controller/application.rb .. I then
"before_filter :check_authentication" from the single controllers in
need of auth.

But this does not suffice. I need to setup "groups", because some of
the controllers should not be accessible to certain groups of users.
So I added a "role" column to User and I was thinking to add a
"check_permission" under application.rb and to add a before_filter
from the proper controllers passing the needed role to it somehow

The problem is that I have no idea on how to pass say "administrator"
to a filter.. I tried check_permission(role) but it doesn't like it at

Any hint? :slight_smile:


In short, you can't. But you can do this:
       def self.require_role role, options = {}
         define_method role +'_required' do
           check_permission role
         protected role+'_required'
         before_filter (role+'_required').to_sym, options
in application.rb (or do whatever you want to have that as a class method)

You can then write
require_role 'admin'
in a controller for example and that will create an admin_required method (that just calls through to check_permission) and set it up as a before_filter.



Thank you, it works just fine :slight_smile:

Well, I panic'd for a couple of minutes.. so, if anyone's reading this
and is willing to use Fred's method, keep in mind to stick
"require_role 'blah'" AFTER the before_filter line or you'll get a nil
related error if the user is not currently logged in