You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

173 lines
4.7 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  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, -> { searchable.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. delegate :accounts_count,
  38. :accounts_count=,
  39. :increment_count!,
  40. :decrement_count!,
  41. to: :account_tag_stat
  42. after_save :save_account_tag_stat
  43. update_index('tags#tag', :self) if Chewy.enabled?
  44. def account_tag_stat
  45. super || build_account_tag_stat
  46. end
  47. def cached_sample_accounts
  48. Rails.cache.fetch("#{cache_key}/sample_accounts", expires_in: 12.hours) { sample_accounts }
  49. end
  50. def to_param
  51. name
  52. end
  53. def usable
  54. boolean_with_default('usable', true)
  55. end
  56. alias usable? usable
  57. def listable
  58. boolean_with_default('listable', true)
  59. end
  60. alias listable? listable
  61. def trendable
  62. boolean_with_default('trendable', false)
  63. end
  64. alias trendable? trendable
  65. def requires_review?
  66. reviewed_at.nil?
  67. end
  68. def reviewed?
  69. reviewed_at.present?
  70. end
  71. def requested_review?
  72. requested_review_at.present?
  73. end
  74. def trending?
  75. TrendingTags.trending?(self)
  76. end
  77. def history
  78. days = []
  79. 7.times do |i|
  80. day = i.days.ago.beginning_of_day.to_i
  81. days << {
  82. day: day.to_s,
  83. uses: Redis.current.get("activity:tags:#{id}:#{day}") || '0',
  84. accounts: Redis.current.pfcount("activity:tags:#{id}:#{day}:accounts").to_s,
  85. }
  86. end
  87. days
  88. end
  89. class << self
  90. def find_or_create_by_names(name_or_names)
  91. Array(name_or_names).map(&method(:normalize)).uniq { |str| str.mb_chars.downcase.to_s }.map do |normalized_name|
  92. tag = matching_name(normalized_name).first || create!(name: normalized_name)
  93. yield tag if block_given?
  94. tag
  95. end
  96. end
  97. def search_for(term, limit = 5, offset = 0)
  98. normalized_term = normalize(term.strip).mb_chars.downcase.to_s
  99. pattern = sanitize_sql_like(normalized_term) + '%'
  100. Tag.listable
  101. .where(arel_table[:name].lower.matches(pattern))
  102. .where(arel_table[:name].lower.eq(normalized_term).or(arel_table[:reviewed_at].not_eq(nil)))
  103. .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