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.

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