Fun with named scopes in Rails

One of the features that I definitely had no idea about when I first learned Rails was named_scope. I went back at look a look at some of the old projects I had worked on I frequently found myself writing a bunch of extra finder conditions or methods in order to achieve that goal.

That is a relatively simple example, but since these conditions are used frequently I can improve upon this by using named scopes. Named scopes allow you to encapsulate some finder arguments into a simple, chain-able, and efficient methods. Here is what the named scope definitions and finder looks like:

While these could be defined as standard methods, you loose a lot of the power and flexibility which named scopes provides. For example, with named scopes I can add in additional arguments or conditions to any of the above methods. For example:

If you are using Rails 2.3 they have added a feature called scoped_by which will dynamically generate a lot of the boiler-plate scopes that you would need.

If you aren't using Rails 2.3 or aren't crazy about that syntax there is also a Ruby gem which provides a lot of the same functionality in an arguably more elegant manner. Its called Pacecar and it made by the guys over at Thoughtbot. Using Pacecar the above example would look like:

That looks a lot more elegant to me. So get out there and start using some named scopes.


Post a Comment