Created
October 27, 2009 13:49
-
-
Save scharfie/219573 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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