Run a business? Check out LessAccounting, our bookkeeping system that'll save you hours per week.

Announcing:

We built the entrepreneur's bookkeeping system, it's called LessAccounting. You'll probably love it.

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.

Business Owners: save hours per week with LessAccounting. It's like Quickbooks, just not total shit.

1 Comment

Kiere El-Shafie
Kiere El-Shafie said on August 10, 2012

Nice. Thanks!

Leave a Comment

About Steven
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.

You Should...

Follow Steven on Twitter
Friend Steven on Facebook
Subscribe
LessEverything Copyright 2011 LessEverything.com
We don't like footers, they're kinda boring