Filter function with parameter


#1

Hi!

I want to add a function with a static paramter (“2” in the example) to
a filter, but somehow Rails seems to be looking for another syntax.

before_filter :check_quantity(2), :only => [:show]

doesn’t work. What’s the right way to do this?

Thanks a lot!


#2

If the parameter is static, then won’t the result be static too? If
so, you could just put in the result.
-Nathan


#3

If the parameter is static, then won’t the result be static too? If
so, you could just put in the result.

No, as a filter has access to other variables as well.

Another example would be:

before_filter :check_authentication(:user), :only => [:list, :show]
before_filter :check_authentication(:admin), :only => [:create, :delete]
(Sure, I could go with two separate functions
(check_admin_authentication and check_user_authentication) in this
particular example.)

I’m sure this feature is commonly needed, so it should be implemented in
Rails. I just don’t know how to use it.


#4

On Jun 4, 2006, at 3:35 AM, mh789 wrote:

(Sure, I could go with two separate functions
Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

You could just give your method a default parameter, and then when

it gets called without a param it will always be 2 but when you call
it form elsewhere you can give it whatever arg you want to.

before_filter :check_quantity, :only => [:show]

def check_quantity(quan = 2)

unless you call with an arg, quan will always be 2.

end

-Ezra


#5

You can use blocks in a before_filter. I’m not at home at the moment
so I have no ruby to check syntax, but something like

before_filter :only => [:show], { check_authentication(:user) }

Sorry if the syntax is not correct. I have used this kind of filter
before to pass parameters to methods. Note that if you need a filter
to make the user avaialbe then you need to call that filter before
this one.

eg
before_filter :set_user
before_filter :only => [:show], { check_authentication(:user) }

Hope this helps


#6

Daniel ----- wrote:

You can use blocks in a before_filter. I’m not at home at the moment
so I have no ruby to check syntax, but something like

before_filter :only => [:show], { check_authentication(:user) }

Thanks a lot, that does the trick!

before_filter(:only => [:create, :delete]) {|controller|
controller.check_authentication(‘admin’) }