Skip to content

Instantly share code, notes, and snippets.

@gogogarrett
Last active December 12, 2015 09:29
Show Gist options
  • Save gogogarrett/4751729 to your computer and use it in GitHub Desktop.
Save gogogarrett/4751729 to your computer and use it in GitHub Desktop.
Harness PGSearch and return back a specific output grouped by core topics to fulfill my searching needs!
class << self
# This will loop through each topic and create an array of objects that are
# found within a specific topic.
#
# Example: CoreTopic.find_by_topic(pg_search_results_array)
# Output: [
# { topic: "teamwork", results: [ob1, obj2, obj3] }
# { topic: "respect", results: [ob1, obj2, obj3] }
# ]
def find_by_topics(results)
results_hash, used = [], []
CoreTopic.all.each do |topic|
found_in_topic = []
results.flatten.each do |result|
result = result.class == PgSearch::Document ? result.searchable : result
break unless result.present?
found_in_topic << result if result.core_topics.include?(topic)
if found_in_topic.include?(result) && !used.include?(result)
results_hash << { topic: topic.title, results: found_in_topic.uniq }
end
used << result if result.core_topics.include?(topic)
end
end
results_hash
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment