tag.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: tags
  5. #
  6. # id :bigint(8) not null, primary key
  7. # name :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. #
  11. class Tag < ApplicationRecord
  12. has_and_belongs_to_many :statuses
  13. has_and_belongs_to_many :accounts
  14. has_and_belongs_to_many :sample_accounts, -> { searchable.discoverable.popular.limit(3) }, class_name: 'Account'
  15. has_one :account_tag_stat, dependent: :destroy
  16. HASHTAG_NAME_RE = '[[:word:]_]*[[:alpha:]_·][[:word:]_]*'
  17. HASHTAG_RE = /(?:^|[^\/\)\w])#(#{HASHTAG_NAME_RE})/i
  18. validates :name, presence: true, uniqueness: true, format: { with: /\A#{HASHTAG_NAME_RE}\z/i }
  19. scope :discoverable, -> { joins(:account_tag_stat).where(AccountTagStat.arel_table[:accounts_count].gt(0)).where(account_tag_stats: { hidden: false }).order(Arel.sql('account_tag_stats.accounts_count desc')) }
  20. scope :hidden, -> { where(account_tag_stats: { hidden: true }) }
  21. delegate :accounts_count,
  22. :accounts_count=,
  23. :increment_count!,
  24. :decrement_count!,
  25. :hidden?,
  26. to: :account_tag_stat
  27. after_save :save_account_tag_stat
  28. def account_tag_stat
  29. super || build_account_tag_stat
  30. end
  31. def cached_sample_accounts
  32. Rails.cache.fetch("#{cache_key}/sample_accounts", expires_in: 12.hours) { sample_accounts }
  33. end
  34. def to_param
  35. name
  36. end
  37. def history
  38. days = []
  39. 7.times do |i|
  40. day = i.days.ago.beginning_of_day.to_i
  41. days << {
  42. day: day.to_s,
  43. uses: Redis.current.get("activity:tags:#{id}:#{day}") || '0',
  44. accounts: Redis.current.pfcount("activity:tags:#{id}:#{day}:accounts").to_s,
  45. }
  46. end
  47. days
  48. end
  49. class << self
  50. def search_for(term, limit = 5)
  51. pattern = sanitize_sql_like(term.strip) + '%'
  52. Tag.where('lower(name) like lower(?)', pattern).order(:name).limit(limit)
  53. end
  54. end
  55. private
  56. def save_account_tag_stat
  57. return unless account_tag_stat&.changed?
  58. account_tag_stat.save
  59. end
  60. end