ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4before-filter

Before filter, calling a method with param throws syntax error. Ruby


im trying to understand why this throws error

before_filter :check_user_validity(params[:user_id])

error:

syntax error, unexpected '(', expecting keyword_end before_filter :check_user_validity(params[:user_id])

but this not:

before_filter -> { check_user_validity(params[:user_id]) }

why we need to use proc or lambda in before filter, for calling methods with params.

for calling methods without params, it doesn't throws error.

can anyone give the particular reason for the why it throws error?


Solution

  • :check_user_validity is a symbol which is something like a string. You can't "run" a symbol with parentheses. You are effectively doing something like 'function_name'(...) which is invalid syntax.

    before_filter or before_action works by passing it a function name (by using symbols) or function (by using proc/lambda) to be called later when a request is received.