account_stat.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: account_stats
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8) not null
  8. # statuses_count :bigint(8) default(0), not null
  9. # following_count :bigint(8) default(0), not null
  10. # followers_count :bigint(8) default(0), not null
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. # last_status_at :datetime
  14. # lock_version :integer default(0), not null
  15. #
  16. class AccountStat < ApplicationRecord
  17. belongs_to :account, inverse_of: :account_stat
  18. update_index('accounts#account', :account)
  19. def increment_count!(key)
  20. update(attributes_for_increment(key))
  21. rescue ActiveRecord::StaleObjectError
  22. begin
  23. reload_with_id
  24. rescue ActiveRecord::RecordNotFound
  25. # Nothing to do
  26. else
  27. retry
  28. end
  29. end
  30. def decrement_count!(key)
  31. update(key => [public_send(key) - 1, 0].max)
  32. rescue ActiveRecord::StaleObjectError
  33. begin
  34. reload_with_id
  35. rescue ActiveRecord::RecordNotFound
  36. # Nothing to do
  37. else
  38. retry
  39. end
  40. end
  41. private
  42. def attributes_for_increment(key)
  43. attrs = { key => public_send(key) + 1 }
  44. attrs[:last_status_at] = Time.now.utc if key == :statuses_count
  45. attrs
  46. end
  47. def reload_with_id
  48. self.id = find_by!(account: account).id if new_record?
  49. reload
  50. end
  51. end