I’m reading The Rails 3 Way and I don’t understand why there’s a proc in the routes. I still have a hard time grasping the use of proc/lambda and how they are used.
How is this:
match 'records/:id' => "records#protected",
:constraints => proc {|req| req.params[:id].to_i < 100 }
different from:
match 'records/:id' => "records#protected",
:constraints => params[:id].to_i < 100
?
Maybe you’re more familiar with JavaScript? Procs are similar to anonymous functions. The first version of your code is roughly equivalent to:
That is,
constraintsis being set to a block of code which can be evaluated at a later time.The second version would be like writing
which is to say, a syntax error, and logically broken as it tries to evaluate
return req.params["id"] < 100immediately as the code is interpreted, beforereqhas even been defined.This is the primary difference between your two versions, and why the
procis important: You need to pass the code into the route so it can be evaluated later when routing occurs.