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

Hi,

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
all

Any hint? :slight_smile:

Thanks

On 11 Mar 2008, at 15:41, fizban wrote:

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
all
In short, you can’t. But you can do this:
Stick
def self.require_role role, options = {}
define_method role +’_required’ do
check_permission role
end
protected role+’_required’
before_filter (role+’_required’).to_sym, options
end
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.

Fred

On 11 Mar, 16:47, Frederick C. [email protected] wrote:

In short, you can’t. But you can do this:
[snip]

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