Skip to content

Instantly share code, notes, and snippets.

@sjtipton
Created March 28, 2013 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjtipton/5264324 to your computer and use it in GitHub Desktop.
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)
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