Skip to content

Instantly share code, notes, and snippets.

@alexistoulotte
Created February 24, 2009 15:51
Show Gist options
  • Save alexistoulotte/69633 to your computer and use it in GitHub Desktop.
Save alexistoulotte/69633 to your computer and use it in GitHub Desktop.
module Sortable
def self.included(base)
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
base.send(:class_inheritable_accessor, :sort_attributes)
base.sort_attributes = []
end
module ClassMethods
def sort_by(*attributes)
self.sort_attributes = attributes
end
end
module InstanceMethods
def <=>(other)
return 1 unless other
self.class.sort_attributes.each do |attribute|
a, b = send(attribute) || 0, other.send(attribute) || 0
return -1 unless a.respond_to?(:'<=>')
result = a <=> b
return result if result && !result.zero?
end
0
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment