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.

120 lines
3.4 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. # score :integer
  11. #
  12. class Tag < ApplicationRecord
  13. has_and_belongs_to_many :statuses
  14. has_and_belongs_to_many :accounts
  15. has_and_belongs_to_many :sample_accounts, -> { searchable.discoverable.popular.limit(3) }, class_name: 'Account'
  16. has_many :featured_tags, dependent: :destroy, inverse_of: :tag
  17. has_one :account_tag_stat, dependent: :destroy
  18. HASHTAG_NAME_RE = '([[:word:]_][[:word:]_·]*[[:alpha:]_·][[:word:]_·]*[[:word:]_])|([[:word:]_]*[[:alpha:]][[:word:]_]*)'
  19. HASHTAG_RE = /(?:^|[^\/\)\w])#(#{HASHTAG_NAME_RE})/i
  20. validates :name, presence: true, format: { with: /\A(#{HASHTAG_NAME_RE})\z/i }
  21. 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')) }
  22. scope :hidden, -> { where(account_tag_stats: { hidden: true }) }
  23. scope :most_used, ->(account) { joins(:statuses).where(statuses: { account: account }).group(:id).order(Arel.sql('count(*) desc')) }
  24. delegate :accounts_count,
  25. :accounts_count=,
  26. :increment_count!,
  27. :decrement_count!,
  28. :hidden?,
  29. to: :account_tag_stat
  30. after_save :save_account_tag_stat
  31. def account_tag_stat
  32. super || build_account_tag_stat
  33. end
  34. def cached_sample_accounts
  35. Rails.cache.fetch("#{cache_key}/sample_accounts", expires_in: 12.hours) { sample_accounts }
  36. end
  37. def to_param
  38. name
  39. end
  40. def history
  41. days = []
  42. 7.times do |i|
  43. day = i.days.ago.beginning_of_day.to_i
  44. days << {
  45. day: day.to_s,
  46. uses: Redis.current.get("activity:tags:#{id}:#{day}") || '0',
  47. accounts: Redis.current.pfcount("activity:tags:#{id}:#{day}:accounts").to_s,
  48. }
  49. end
  50. days
  51. end
  52. class << self
  53. def find_or_create_by_names(name_or_names)
  54. Array(name_or_names).map(&method(:normalize)).uniq { |str| str.mb_chars.downcase.to_s }.map do |normalized_name|
  55. tag = matching_name(normalized_name).first || create(name: normalized_name)
  56. yield tag if block_given?
  57. tag
  58. end
  59. end
  60. def search_for(term, limit = 5, offset = 0)
  61. normalized_term = normalize(term.strip).mb_chars.downcase.to_s
  62. pattern = sanitize_sql_like(normalized_term) + '%'
  63. Tag.where(arel_table[:name].lower.matches(pattern))
  64. .where(arel_table[:score].gt(0).or(arel_table[:name].lower.eq(normalized_term)))
  65. .order(Arel.sql('length(name) ASC, score DESC, name ASC'))
  66. .limit(limit)
  67. .offset(offset)
  68. end
  69. def find_normalized(name)
  70. matching_name(name).first
  71. end
  72. def find_normalized!(name)
  73. find_normalized(name) || raise(ActiveRecord::RecordNotFound)
  74. end
  75. def matching_name(name_or_names)
  76. names = Array(name_or_names).map { |name| normalize(name).mb_chars.downcase.to_s }
  77. if names.size == 1
  78. where(arel_table[:name].lower.eq(names.first))
  79. else
  80. where(arel_table[:name].lower.in(names))
  81. end
  82. end
  83. private
  84. def normalize(str)
  85. str.gsub(/\A#/, '')
  86. end
  87. end
  88. private
  89. def save_account_tag_stat
  90. return unless account_tag_stat&.changed?
  91. account_tag_stat.save
  92. end
  93. end