Practical eCommerce

 

Rails 2.1

A look at the great new features including named scope

Author: BJ Clark
Publish Date: July 28, 2008
Blog: Developers' Corner
Tags: ruby on rails, development

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.

Add a Bookmark: Add 'Rails 2.1' to Del.icio.us Digg 'Rails 2.1' on Digg.com Submit 'Rails 2.1' to reddit.com Blink 'Rails 2.1' Add 'Rails 2.1' to dzone Seed 'Rails 2.1' on Newsvine Add 'Rails 2.1' to Furl Add 'Rails 2.1' to Spurl Add 'Rails 2.1' on simpy.com Add 'Rails 2.1' to fark.com BlogMark 'Rails 2.1' Add 'Rails 2.1' to Yahoo! myweb2 Add 'Rails 2.1' to wists.com Stumble It!

1 Comment

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

View A Sample | Privacy

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.

Inside Practical eCommerce