Forum: Ruby on Rails how to override enumerable compare for attributes?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A822370edefad22484f9260fb787c710?d=identicon&s=25 Ed (Guest)
on 2008-11-20 18:56
(Received via mailing list)
How would I override <=> for certain attributes of a class?

Say I have the following:

class Workout < ActiveRecord::Base
# columns in db:  time, weight, reps, distance
end

I want to be able to sort by results, to list workouts by best time,
weight, etc.  But the ordering is different, because a low time is
better than a high time, while a high weight is better than a low
weight, etc.

Right now I'm doing a class method with an if statement like this:

def self.ranked_by(compare)
  if compare == :time
    find(:all).sort_by{|workout| workout.time}.reverse
  else
    find(:all).sort_by{|workout| workout.send(compare)}
  end
end

That works, but it's ugly and the ugliness tends to replicate itself.
I could simplify my code by overriding the <=> method for the time
attribute so that I could simply do:

def self.ranked_by(compare)
  find(:all).sort_by{|workout| workout.send(compare)}
end

But how to do that?
This topic is locked and can not be replied to.