Created
September 14, 2016 20:37
-
-
Save mfifth/b67ffe6b1324700bf30bdb15e3ead6b4 to your computer and use it in GitHub Desktop.
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
# SortCollectionRelevancy | |
# | |
# Sort any collection (array), with specific methods based on the word frequency | |
class SortCollectionRelevancy | |
def initialize(query, collection, methods = []) | |
@query = query | |
@collection = collection | |
@methods = Array(methods) | |
end | |
def sort | |
sort_collection(@query, @collection, @methods) | |
end | |
protected | |
def sort_collection(query, collection, methods) | |
query_words = normalize_words(query).uniq | |
collection.sort_by.with_index do |record, i| | |
word_count = methods.flat_map do |method| | |
normalize_words(record.send(method)) | |
end.inject(Hash.new(0)) { |h, v| h.tap { h[v] += 1 }} | |
-word_count.values_at(*query_words).sum | |
end | |
end | |
def normalize_words(value) | |
value.split(/\W+/).map(&:downcase) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment