Lambdas and Procs in Named Scopes
written by Steven on August 09, 2012
Most people don't know this, but you can use a Proc instead of a lambda in your named scope. Here's an example:
Here we have two scopes that do the same thing. They take a param and if it's blank they don't scope anything and if it's not blank they scope based on it. And as you can see, thus far they are exactly the same thing. You can use a Proc.
But why would you? Because our rubyfu is strong we know that a Proc will ignore empty arguments but a lambda will raise on them. So we choose the one that best fits our needs. Here's what the two look like:
In our last example we show the usage of calling the scope with a Proc. The thing we are passing might be security code, an STI kind of switch, which direction to order, or more likely something specific to your app that is easiest to put right here. In the normal case we're passing something into the scope that get's evaluated. But in the rare case where we don't need to pass anything, I prefer to pass nothing than passing a contrived parameter like an empty string or nil.
I'm not saying you should do any of this. I'm just showing you that you can.
Leave a Comment

Steven Bristol has written code for the past 20 years. He like green vegetables and kittens, oh and butterflies too. He loves to throw ninja stars at his enemies.

1 Comment
Nice. Thanks!