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?
CodePudding user response:
It's because Rails framework was designed like that.
You're not calling a method check_user_validity
itself, but rather calling an special ApplicationController
class method before_filter
, passing a parameter with a symbol that is a method name you want to call before some actions. In your case it's :check_user_validity
.
You can also pass a lambda to before_filter
if you want your method to be called with some arguments.
Also, there is no need to pass params[:user_id]
to this method as all controller instance methods have access to params
. So you can just go like this:
def check_user_validity
user_id = params[:user_id]
...
end
CodePudding user response:
: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.