tag.rb 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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_many :featured_tags, dependent: :destroy, inverse_of: :tag
  23. HASHTAG_SEPARATORS = "_\u00B7\u200c"
  24. HASHTAG_NAME_RE = "([[:word:]_][[:word:]#{HASHTAG_SEPARATORS}]*[[:alpha:]#{HASHTAG_SEPARATORS}][[:word:]#{HASHTAG_SEPARATORS}]*[[:word:]_])|([[:word:]_]*[[:alpha:]][[:word:]_]*)"
  25. HASHTAG_RE = /(?:^|[^\/\)\w])#(#{HASHTAG_NAME_RE})/i
  26. validates :name, presence: true, format: { with: /\A(#{HASHTAG_NAME_RE})\z/i }
  27. validate :validate_name_change, if: -> { !new_record? && name_changed? }
  28. scope :reviewed, -> { where.not(reviewed_at: nil) }
  29. scope :unreviewed, -> { where(reviewed_at: nil) }
  30. scope :pending_review, -> { unreviewed.where.not(requested_review_at: nil) }
  31. scope :usable, -> { where(usable: [true, nil]) }
  32. scope :listable, -> { where(listable: [true, nil]) }
  33. scope :trendable, -> { Setting.trendable_by_default ? where(trendable: [true, nil]) : where(trendable: true) }
  34. scope :not_trendable, -> { where(trendable: false) }
  35. scope :recently_used, ->(account) { joins(:statuses).where(statuses: { id: account.statuses.select(:id).limit(1000) }).group(:id).order(Arel.sql('count(*) desc')) }
  36. scope :matches_name, ->(term) { where(arel_table[:name].lower.matches(arel_table.lower("#{sanitize_sql_like(Tag.normalize(term))}%"), nil, true)) } # Search with case-sensitive to use B-tree index
  37. update_index('tags', :self)
  38. def to_param
  39. name
  40. end
  41. def usable
  42. boolean_with_default('usable', true)
  43. end
  44. alias usable? usable
  45. def listable
  46. boolean_with_default('listable', true)
  47. end
  48. alias listable? listable
  49. def trendable
  50. boolean_with_default('trendable', Setting.trendable_by_default)
  51. end
  52. alias trendable? trendable
  53. def requires_review?
  54. reviewed_at.nil?
  55. end
  56. def reviewed?
  57. reviewed_at.present?
  58. end
  59. def requested_review?
  60. requested_review_at.present?
  61. end
  62. def requires_review_notification?
  63. requires_review? && !requested_review?
  64. end
  65. def decaying?
  66. max_score_at && max_score_at >= Trends.tags.options[:max_score_cooldown].ago && max_score_at < 1.day.ago
  67. end
  68. def history
  69. @history ||= Trends::History.new('tags', id)
  70. end
  71. class << self
  72. def find_or_create_by_names(name_or_names)
  73. Array(name_or_names).map(&method(:normalize)).uniq { |str| str.mb_chars.downcase.to_s }.map do |normalized_name|
  74. tag = matching_name(normalized_name).first || create(name: normalized_name)
  75. yield tag if block_given?
  76. tag
  77. end
  78. end
  79. def search_for(term, limit = 5, offset = 0, options = {})
  80. stripped_term = term.strip
  81. query = Tag.listable.matches_name(stripped_term)
  82. query = query.merge(matching_name(stripped_term).or(where.not(reviewed_at: nil))) if options[:exclude_unreviewed]
  83. query.order(Arel.sql('length(name) ASC, name ASC'))
  84. .limit(limit)
  85. .offset(offset)
  86. end
  87. def find_normalized(name)
  88. matching_name(name).first
  89. end
  90. def find_normalized!(name)
  91. find_normalized(name) || raise(ActiveRecord::RecordNotFound)
  92. end
  93. def matching_name(name_or_names)
  94. names = Array(name_or_names).map { |name| arel_table.lower(normalize(name)) }
  95. if names.size == 1
  96. where(arel_table[:name].lower.eq(names.first))
  97. else
  98. where(arel_table[:name].lower.in(names))
  99. end
  100. end
  101. def normalize(str)
  102. str.gsub(/\A#/, '')
  103. end
  104. end
  105. private
  106. def validate_name_change
  107. errors.add(:name, I18n.t('tags.does_not_match_previous_name')) unless name_was.mb_chars.casecmp(name.mb_chars).zero?
  108. end
  109. end