From 2e0350ee742c178ee22d6987c2da2755f72d9123 Mon Sep 17 00:00:00 2001 From: Arpit Jalan Date: Wed, 11 May 2016 15:23:54 +0530 Subject: [PATCH] FEATURE: new search filter - #category-slug --- lib/search.rb | 18 ++++++++++++++++++ spec/components/search_spec.rb | 19 ++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/search.rb b/lib/search.rb index d66bfa939..17547d9fa 100644 --- a/lib/search.rb +++ b/lib/search.rb @@ -279,6 +279,24 @@ class Search end end + advanced_filter(/^\#([a-zA-Z0-9,\-:]+)/) do |posts,match| + slug = match.to_s.split(":") + if slug[1] + # sub category + parent_category_id = Category.where(slug: slug[0].downcase, parent_category_id: nil).pluck(:id).first + category_id = Category.where(slug: slug[1].downcase, parent_category_id: parent_category_id).pluck(:id).first + else + # main category + category_id = Category.where(slug: slug[0].downcase, parent_category_id: nil).pluck(:id).first + end + + if category_id + posts.where("topics.category_id = ?", category_id) + else + posts.where("1 = 0") + end + end + advanced_filter(/group:(.+)/) do |posts,match| group_id = Group.where('name ilike ? OR (id = ? AND id > 0)', match, match.to_i).pluck(:id).first if group_id diff --git a/spec/components/search_spec.rb b/spec/components/search_spec.rb index 7a0e58064..af371932f 100644 --- a/spec/components/search_spec.rb +++ b/spec/components/search_spec.rb @@ -526,6 +526,24 @@ describe Search do expect(Search.execute('sam order:latest').posts.map(&:id)).to eq([post2.id, post1.id]) end + + it 'supports category slug' do + # main category + category = Fabricate(:category, name: 'category 24', slug: 'category-24') + topic = Fabricate(:topic, created_at: 3.months.ago, category: category) + post = Fabricate(:post, raw: 'hi this is a test 123', topic: topic) + + expect(Search.execute('this is a test #category-24').posts.length).to eq(1) + expect(Search.execute('this is a test #category-25').posts.length).to eq(0) + + # sub category + sub_category = Fabricate(:category, name: 'sub category', slug: 'sub-category', parent_category_id: category.id) + second_topic = Fabricate(:topic, created_at: 3.months.ago, category: sub_category) + second_topic_post = Fabricate(:post, raw: 'hi testing again 123', topic: second_topic) + + expect(Search.execute('testing again #category-24:sub-category').posts.length).to eq(1) + expect(Search.execute('testing again #sub-category').posts.length).to eq(0) + end end it 'can parse complex strings using ts_query helper' do @@ -566,4 +584,3 @@ describe Search do end end -