Rails 2.1

 
avatar

If you haven’t heard by now (and there’s no excuse if you haven’t), Rails 2.1 was released last month at RailsConf in Portland. So what’s the big deal you ask? Well, there’s lots of cool new features and improvements: dirty tracking, gem dependencies (finally), better caching, better time zone support and my favorite, Named Scope.

Named Scope? It doesn’t exactly sound like a big deal, but it is. Have you ever written code like this:

@products = Products.find :all, :conditions => [“price < ? AND  price > ?”, params[:products][:highest_price], params[:products][:lowest_price]]

I know I’m guilty of it, and it’s just plain nasty. How did that sql get in my skinny controller?!? I don’t know. So I re-factored it like this:

@products = Products.all_by_price(params[:products][:highest_price], params[:products][:lowest_price])

But that is pretty nasty too, just one notch better than our first example. The code is going to be a pain to extend, it’s not very clear what it actually does, and I bet you’d have to look at the model to know which price comes first, wouldn’t you?

So what if I told you I could replace that code with something like this:

@products = Products.find(:all).higher_than(params[:products][:lowest_price]).lower_than(params[:products][:highest_price])

How slick is that? Extensible, infinitely more reusable, completely clear of it’s function, and it reads like poetry (ok, maybe not the poetry bit). That’s a named scope, and it’s available in Rails 2.1.

So how do you find out more? Why not check out and excellent railscast on the subject or one of Ryan’s Scraps.

Category: Developers' Corner | Tags: ruby on rails, development

1 Comment

Rss-sm

Sign-up to receive EcommerceNotes, our acclaimed email newsletter.

View A Sample | Privacy

Connect with us

Bloggers Wanted

We’re looking for merchants and other ecommerce professionals to share their experiences with our readers. If this interests you, we invite you to contact us.

Help

Featured Tags | All A-Z

 

Inside Practical eCommerce