|
| 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) |
| 8 | +# tag_id :bigint(8) |
| 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 | +# |
| 14 | + |
| 15 | +class FeaturedTag < ApplicationRecord |
| 16 | + belongs_to :account, inverse_of: :featured_tags, required: true |
| 17 | + belongs_to :tag, inverse_of: :featured_tags, required: true |
| 18 | + |
| 19 | + delegate :name, to: :tag, allow_nil: true |
| 20 | + |
| 21 | + validates :name, presence: true |
| 22 | + validate :validate_featured_tags_limit, on: :create |
| 23 | + |
| 24 | + def name=(str) |
| 25 | + self.tag = Tag.find_or_initialize_by(name: str.delete('#').mb_chars.downcase.to_s) |
| 26 | + end |
| 27 | + |
| 28 | + def increment(timestamp) |
| 29 | + update(statuses_count: statuses_count + 1, last_status_at: timestamp) |
| 30 | + end |
| 31 | + |
| 32 | + def decrement(deleted_status_id) |
| 33 | + 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) |
| 34 | + end |
| 35 | + |
| 36 | + def reset_data |
| 37 | + self.statuses_count = account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).count |
| 38 | + self.last_status_at = account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).select(:created_at).first&.created_at |
| 39 | + end |
| 40 | + |
| 41 | + private |
| 42 | + |
| 43 | + def validate_featured_tags_limit |
| 44 | + errors.add(:base, I18n.t('featured_tags.errors.limit')) if account.featured_tags.count >= 10 |
| 45 | + end |
| 46 | +end |
0 commit comments