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.

91 lines
2.5 KiB

8 years ago
8 years ago
8 years ago
8 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. #
  11. class Tag < ApplicationRecord
  12. has_and_belongs_to_many :statuses
  13. has_and_belongs_to_many :accounts
  14. has_and_belongs_to_many :sample_accounts, -> { searchable.discoverable.popular.limit(3) }, class_name: 'Account'
  15. has_many :featured_tags, dependent: :destroy, inverse_of: :tag
  16. has_one :account_tag_stat, dependent: :destroy
  17. HASHTAG_NAME_RE = '[[:word:]_]*[[:alpha:]_·][[:word:]_]*'
  18. HASHTAG_RE = /(?:^|[^\/\)\w])#(#{HASHTAG_NAME_RE})/i
  19. validates :name, presence: true, uniqueness: true, format: { with: /\A#{HASHTAG_NAME_RE}\z/i }
  20. 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')) }
  21. scope :hidden, -> { where(account_tag_stats: { hidden: true }) }
  22. scope :most_used, ->(account) { joins(:statuses).where(statuses: { account: account }).group(:id).order(Arel.sql('count(*) desc')) }
  23. delegate :accounts_count,
  24. :accounts_count=,
  25. :increment_count!,
  26. :decrement_count!,
  27. :hidden?,
  28. to: :account_tag_stat
  29. after_save :save_account_tag_stat
  30. def account_tag_stat
  31. super || build_account_tag_stat
  32. end
  33. def cached_sample_accounts
  34. Rails.cache.fetch("#{cache_key}/sample_accounts", expires_in: 12.hours) { sample_accounts }
  35. end
  36. def to_param
  37. name
  38. end
  39. def history
  40. days = []
  41. 7.times do |i|
  42. day = i.days.ago.beginning_of_day.to_i
  43. days << {
  44. day: day.to_s,
  45. uses: Redis.current.get("activity:tags:#{id}:#{day}") || '0',
  46. accounts: Redis.current.pfcount("activity:tags:#{id}:#{day}:accounts").to_s,
  47. }
  48. end
  49. days
  50. end
  51. class << self
  52. def search_for(term, limit = 5, offset = 0)
  53. pattern = sanitize_sql_like(term.strip) + '%'
  54. Tag.where('lower(name) like lower(?)', pattern)
  55. .order(:name)
  56. .limit(limit)
  57. .offset(offset)
  58. end
  59. def find_normalized(name)
  60. find_by(name: name.mb_chars.downcase.to_s)
  61. end
  62. def find_normalized!(name)
  63. find_normalized(name) || raise(ActiveRecord::RecordNotFound)
  64. end
  65. end
  66. private
  67. def save_account_tag_stat
  68. return unless account_tag_stat&.changed?
  69. account_tag_stat.save
  70. end
  71. end