about summary refs log tree commit diff
path: root/app/models
diff options
context:
space:
mode:
Diffstat (limited to 'app/models')
-rw-r--r--app/models/tag.rb9
-rw-r--r--app/models/trending_tags.rb7
2 files changed, 12 insertions, 4 deletions
diff --git a/app/models/tag.rb b/app/models/tag.rb
index 46e3a3ec0..c7f0af86d 100644
--- a/app/models/tag.rb
+++ b/app/models/tag.rb
@@ -7,6 +7,7 @@
 #  name       :string           default(""), not null
 #  created_at :datetime         not null
 #  updated_at :datetime         not null
+#  score      :integer
 #
 
 class Tag < ApplicationRecord
@@ -75,10 +76,12 @@ class Tag < ApplicationRecord
     end
 
     def search_for(term, limit = 5, offset = 0)
-      pattern = sanitize_sql_like(normalize(term.strip)) + '%'
+      normalized_term = normalize(term.strip).mb_chars.downcase.to_s
+      pattern         = sanitize_sql_like(normalized_term) + '%'
 
-      Tag.where(arel_table[:name].lower.matches(pattern.mb_chars.downcase.to_s))
-         .order(:name)
+      Tag.where(arel_table[:name].lower.matches(pattern))
+         .where(arel_table[:score].gt(0).or(arel_table[:name].lower.eq(normalized_term)))
+         .order(Arel.sql('length(name) ASC, score DESC, name ASC'))
          .limit(limit)
          .offset(offset)
     end
diff --git a/app/models/trending_tags.rb b/app/models/trending_tags.rb
index 148535c21..211c8f1dc 100644
--- a/app/models/trending_tags.rb
+++ b/app/models/trending_tags.rb
@@ -48,12 +48,17 @@ class TrendingTags
         redis.zrem(key, tag_id.to_s)
       else
         score = ((observed - expected)**2) / expected
-        redis.zadd(key, score, tag_id.to_s)
+        added = redis.zadd(key, score, tag_id.to_s)
+        bump_tag_score!(tag_id) if added
       end
 
       redis.expire(key, EXPIRE_TRENDS_AFTER)
     end
 
+    def bump_tag_score!(tag_id)
+      Tag.where(id: tag_id).update_all('score = COALESCE(score, 0) + 1')
+    end
+
     def disallowed_hashtags
       return @disallowed_hashtags if defined?(@disallowed_hashtags)