Created
March 28, 2013 15:54
-
-
Save sjtipton/5264324 to your computer and use it in GitHub Desktop.
Sort a collection of hash key-value pairs (e.g. facets returned from a Websolr search)
This file contains 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 SortableCollection | |
class Sorter | |
def self.sort_collection(collection, opts={}) | |
options = opts.select { |k,v| (k.in? valid_sorting_options) && (v.in? valid_sorters) } | |
current_sorter = options[:sort_by].to_sym | |
if options[:direction] == "asc" | |
collection.sort { |a,b| a[current_sorter] <=> b[current_sorter] } | |
else | |
collection.sort { |a,b| b[current_sorter] <=> a[current_sorter] } | |
end | |
end | |
def self.valid_sorting_options | |
[:sort_by, :direction] | |
end | |
def self.valid_sorters | |
%w(number_of_postings employer_name asc desc) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment