Commit 37e45606c640aae38d6e92a902a0b241967b46fe

Authored by Victor Costa
2 parents 2287ee28 a85eeffd

Merge branch 'pg_search_rank' into staging

plugins/pg_search/lib/ext/active_record.rb
@@ -4,7 +4,9 @@ class ActiveRecord::Base @@ -4,7 +4,9 @@ class ActiveRecord::Base
4 def self.pg_search_plugin_search(query) 4 def self.pg_search_plugin_search(query)
5 filtered_query = query.gsub(/[\|\(\)\\\/\s\[\]'"*%&!:]/,' ').split.map{|w| w += ":*"}.join('|') 5 filtered_query = query.gsub(/[\|\(\)\\\/\s\[\]'"*%&!:]/,' ').split.map{|w| w += ":*"}.join('|')
6 if defined?(self::SEARCHABLE_FIELDS) 6 if defined?(self::SEARCHABLE_FIELDS)
7 - where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')") 7 + select("*,ts_rank(to_tsvector('simple', #{pg_search_plugin_fields}), to_tsquery('#{filtered_query}')) as rank").
  8 + where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')").
  9 + order("rank DESC")
8 else 10 else
9 raise "No searchable fields defined for #{self.name}" 11 raise "No searchable fields defined for #{self.name}"
10 end 12 end
plugins/pg_search/test/unit/pg_search_plugin_test.rb
@@ -21,6 +21,13 @@ class PgSearchPluginTest < ActiveSupport::TestCase @@ -21,6 +21,13 @@ class PgSearchPluginTest < ActiveSupport::TestCase
21 assert_includes search(Profile, 'admin deb'), profile2 21 assert_includes search(Profile, 'admin deb'), profile2
22 end 22 end
23 23
  24 + should 'rank profiles based on the search entry' do
  25 + profile1 = fast_create(Profile, :identifier => 'profile1', :name => 'debugger')
  26 + profile2 = fast_create(Profile, :identifier => 'profile2', :name => 'profile admin debugger')
  27 + profile3 = fast_create(Profile, :identifier => 'profile3', :name => 'admin debugger')
  28 + assert_equal [profile2, profile3, profile1], search(Profile, 'profile admin deb')
  29 + end
  30 +
24 should 'locate profile escaping special characters' do 31 should 'locate profile escaping special characters' do
25 profile = fast_create(Profile, :name => 'John', :identifier => 'waterfall') 32 profile = fast_create(Profile, :name => 'John', :identifier => 'waterfall')
26 assert_includes search(Profile, ') ( /\/\/\/\/\ o_o oOo o_o /\/\/\/\/\ ) ((tx waterfall)'), profile 33 assert_includes search(Profile, ') ( /\/\/\/\/\ o_o oOo o_o /\/\/\/\/\ ) ((tx waterfall)'), profile