featured_tag.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: featured_tags
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8) not null
  8. # tag_id :bigint(8) not null
  9. # statuses_count :bigint(8) default(0), not null
  10. # last_status_at :datetime
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. # name :string
  14. #
  15. class FeaturedTag < ApplicationRecord
  16. belongs_to :account, inverse_of: :featured_tags
  17. belongs_to :tag, inverse_of: :featured_tags, optional: true # Set after validation
  18. validates :name, presence: true, format: { with: Tag::HASHTAG_NAME_RE }, on: :create
  19. validate :validate_tag_uniqueness, on: :create
  20. validate :validate_featured_tags_limit, on: :create
  21. before_validation :strip_name
  22. before_create :set_tag
  23. before_create :reset_data
  24. scope :by_name, ->(name) { joins(:tag).where(tag: { name: HashtagNormalizer.new.normalize(name) }) }
  25. LIMIT = 10
  26. def sign?
  27. true
  28. end
  29. def display_name
  30. attributes['name'] || tag.display_name
  31. end
  32. def increment(timestamp)
  33. update(statuses_count: statuses_count + 1, last_status_at: timestamp)
  34. end
  35. def decrement(deleted_status_id)
  36. update(statuses_count: [0, statuses_count - 1].max, last_status_at: account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).where.not(id: deleted_status_id).select(:created_at).first&.created_at)
  37. end
  38. private
  39. def strip_name
  40. self.name = name&.strip&.gsub(/\A#/, '')
  41. end
  42. def set_tag
  43. self.tag = Tag.find_or_create_by_names(name)&.first
  44. end
  45. def reset_data
  46. self.statuses_count = account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).count
  47. self.last_status_at = account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).select(:created_at).first&.created_at
  48. end
  49. def validate_featured_tags_limit
  50. return unless account.local?
  51. errors.add(:base, I18n.t('featured_tags.errors.limit')) if account.featured_tags.count >= LIMIT
  52. end
  53. def validate_tag_uniqueness
  54. errors.add(:name, :taken) if FeaturedTag.by_name(name).where(account_id: account_id).exists?
  55. end
  56. end