This post originated from an RSS feed registered with Ruby Buzz
by Obie Fernandez.
Original Post: Sortable ActiveRecord Models
Feed Title: Obie On Rails (Has It Been 9 Years Already?)
Feed URL: http://jroller.com/obie/feed/entries/rss
Feed Description: Obie Fernandez talks about life as a technologist, mostly as ramblings about software development and consulting. Nowadays it's pretty much all about Ruby and Ruby on Rails.
Most of the time you should let your database order your ActiveRecord models, but every once in awhile you need to order an array of them using Ruby's sort method. Here's a neat little hack which might be useful to you if have a bunch of models with name attributes:
classActiveRecord::Basedef<=>(other)if respond_to?(:name) and other.respond_to?(:name)
name <=> other.name
elsesuperendendend
You can keep extensions like this one in a directory named /lib/core_ext of your Rails application. Remember to require it in your environment.rb file, and that like any Ruby script that is explicitly required, it won't reload dynamically when changed. (server restart needed)