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.

63 lines
1.5 KiB

  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, ActiveRecord::RecordNotUnique
  22. begin
  23. reload_with_id
  24. rescue ActiveRecord::RecordNotFound
  25. return
  26. end
  27. retry
  28. end
  29. def decrement_count!(key)
  30. update(attributes_for_decrement(key))
  31. rescue ActiveRecord::StaleObjectError, ActiveRecord::RecordNotUnique
  32. begin
  33. reload_with_id
  34. rescue ActiveRecord::RecordNotFound
  35. return
  36. end
  37. retry
  38. end
  39. private
  40. def attributes_for_increment(key)
  41. attrs = { key => public_send(key) + 1 }
  42. attrs[:last_status_at] = Time.now.utc if key == :statuses_count
  43. attrs
  44. end
  45. def attributes_for_decrement(key)
  46. attrs = { key => [public_send(key) - 1, 0].max }
  47. attrs
  48. end
  49. def reload_with_id
  50. self.id = self.class.find_by!(account: account).id if new_record?
  51. reload
  52. end
  53. end