Skip to content

Instantly share code, notes, and snippets.

@scharfie
Created October 27, 2009 13:49
Show Gist options
  • Save scharfie/219573 to your computer and use it in GitHub Desktop.
Save scharfie/219573 to your computer and use it in GitHub Desktop.
module SortableBy
module ClassMethods
# defines a 'sorted_by' named scope, which accepts a column name and optional direction
# example: sortable_by :columns => %w(id name)
# usage: SomeModel.sorted_by('name', 'asc')
def sortable_by(options)
class_eval "def self.sortable_columns; #{options[:columns].inspect}; end"
named_scope :sorted_by, Proc.new { |column, direction|
if sortable_columns.include?(column)
direction = direction.downcase
direction = 'asc' unless %w(asc desc).include?(direction)
{ :order => "#{column} #{direction}" }
else
{}
end
}
end
end
def self.included(base)
base.extend ClassMethods
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment