tag.rb 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. # usable :boolean
  11. # trendable :boolean
  12. # listable :boolean
  13. # reviewed_at :datetime
  14. # requested_review_at :datetime
  15. # last_status_at :datetime
  16. # max_score :float
  17. # max_score_at :datetime
  18. #
  19. class Tag < ApplicationRecord
  20. has_and_belongs_to_many :statuses
  21. has_and_belongs_to_many :accounts
  22. has_and_belongs_to_many :sample_accounts, -> { local.discoverable.popular.limit(3) }, class_name: 'Account'
  23. has_many :featured_tags, dependent: :destroy, inverse_of: :tag
  24. has_one :account_tag_stat, dependent: :destroy
  25. HASHTAG_SEPARATORS = "_\u00B7\u200c"
  26. HASHTAG_NAME_RE = "([[:word:]_][[:word:]#{HASHTAG_SEPARATORS}]*[[:alpha:]#{HASHTAG_SEPARATORS}][[:word:]#{HASHTAG_SEPARATORS}]*[[:word:]_])|([[:word:]_]*[[:alpha:]][[:word:]_]*)"
  27. HASHTAG_RE = /(?:^|[^\/\)\w])#(#{HASHTAG_NAME_RE})/i
  28. validates :name, presence: true, format: { with: /\A(#{HASHTAG_NAME_RE})\z/i }
  29. validate :validate_name_change, if: -> { !new_record? && name_changed? }
  30. scope :reviewed, -> { where.not(reviewed_at: nil) }
  31. scope :unreviewed, -> { where(reviewed_at: nil) }
  32. scope :pending_review, -> { unreviewed.where.not(requested_review_at: nil) }
  33. scope :usable, -> { where(usable: [true, nil]) }
  34. scope :listable, -> { where(listable: [true, nil]) }
  35. scope :discoverable, -> { listable.joins(:account_tag_stat).where(AccountTagStat.arel_table[:accounts_count].gt(0)).order(Arel.sql('account_tag_stats.accounts_count desc')) }
  36. scope :most_used, ->(account) { joins(:statuses).where(statuses: { account: account }).group(:id).order(Arel.sql('count(*) desc')) }
  37. scope :matches_name, ->(value) { where(arel_table[:name].matches("#{value}%")) }
  38. delegate :accounts_count,
  39. :accounts_count=,
  40. :increment_count!,
  41. :decrement_count!,
  42. to: :account_tag_stat
  43. after_save :save_account_tag_stat
  44. update_index('tags#tag', :self) if Chewy.enabled?
  45. def account_tag_stat
  46. super || build_account_tag_stat
  47. end
  48. def cached_sample_accounts
  49. Rails.cache.fetch("#{cache_key}/sample_accounts", expires_in: 12.hours) { sample_accounts }
  50. end
  51. def to_param
  52. name
  53. end
  54. def usable
  55. boolean_with_default('usable', true)
  56. end
  57. alias usable? usable
  58. def listable
  59. boolean_with_default('listable', true)
  60. end
  61. alias listable? listable
  62. def trendable
  63. boolean_with_default('trendable', false)
  64. end
  65. alias trendable? trendable
  66. def requires_review?
  67. reviewed_at.nil?
  68. end
  69. def reviewed?
  70. reviewed_at.present?
  71. end
  72. def requested_review?
  73. requested_review_at.present?
  74. end
  75. def trending?
  76. TrendingTags.trending?(self)
  77. end
  78. def history
  79. days = []
  80. 7.times do |i|
  81. day = i.days.ago.beginning_of_day.to_i
  82. days << {
  83. day: day.to_s,
  84. uses: Redis.current.get("activity:tags:#{id}:#{day}") || '0',
  85. accounts: Redis.current.pfcount("activity:tags:#{id}:#{day}:accounts").to_s,
  86. }
  87. end
  88. days
  89. end
  90. class << self
  91. def find_or_create_by_names(name_or_names)
  92. Array(name_or_names).map(&method(:normalize)).uniq { |str| str.mb_chars.downcase.to_s }.map do |normalized_name|
  93. tag = matching_name(normalized_name).first || create!(name: normalized_name)
  94. yield tag if block_given?
  95. tag
  96. end
  97. end
  98. def search_for(term, limit = 5, offset = 0, options = {})
  99. normalized_term = normalize(term.strip).mb_chars.downcase.to_s
  100. pattern = sanitize_sql_like(normalized_term) + '%'
  101. query = Tag.listable.where(arel_table[:name].lower.matches(pattern))
  102. query = query.where(arel_table[:name].lower.eq(normalized_term).or(arel_table[:reviewed_at].not_eq(nil))) if options[:exclude_unreviewed]
  103. query.order(Arel.sql('length(name) ASC, name ASC'))
  104. .limit(limit)
  105. .offset(offset)
  106. end
  107. def find_normalized(name)
  108. matching_name(name).first
  109. end
  110. def find_normalized!(name)
  111. find_normalized(name) || raise(ActiveRecord::RecordNotFound)
  112. end
  113. def matching_name(name_or_names)
  114. names = Array(name_or_names).map { |name| normalize(name).mb_chars.downcase.to_s }
  115. if names.size == 1
  116. where(arel_table[:name].lower.eq(names.first))
  117. else
  118. where(arel_table[:name].lower.in(names))
  119. end
  120. end
  121. private
  122. def normalize(str)
  123. str.gsub(/\A#/, '')
  124. end
  125. end
  126. private
  127. def save_account_tag_stat
  128. return unless account_tag_stat&.changed?
  129. account_tag_stat.save
  130. end
  131. def validate_name_change
  132. errors.add(:name, I18n.t('tags.does_not_match_previous_name')) unless name_was.mb_chars.casecmp(name.mb_chars).zero?
  133. end
  134. end