subscription.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: subscriptions
  5. #
  6. # id :integer not null, primary key
  7. # callback_url :string default(""), not null
  8. # secret :string
  9. # expires_at :datetime
  10. # confirmed :boolean default(FALSE), not null
  11. # account_id :integer not null
  12. # created_at :datetime not null
  13. # updated_at :datetime not null
  14. # last_successful_delivery_at :datetime
  15. # domain :string
  16. #
  17. class Subscription < ApplicationRecord
  18. MIN_EXPIRATION = 1.day.to_i
  19. MAX_EXPIRATION = 30.days.to_i
  20. belongs_to :account, required: true
  21. validates :callback_url, presence: true
  22. validates :callback_url, uniqueness: { scope: :account_id }
  23. scope :confirmed, -> { where(confirmed: true) }
  24. scope :future_expiration, -> { where(arel_table[:expires_at].gt(Time.now.utc)) }
  25. scope :expired, -> { where(arel_table[:expires_at].lt(Time.now.utc)) }
  26. scope :active, -> { confirmed.future_expiration }
  27. def lease_seconds=(value)
  28. self.expires_at = future_expiration(value)
  29. end
  30. def lease_seconds
  31. (expires_at - Time.now.utc).to_i
  32. end
  33. def expired?
  34. Time.now.utc > expires_at
  35. end
  36. before_validation :set_min_expiration
  37. private
  38. def future_expiration(value)
  39. Time.now.utc + future_offset(value).seconds
  40. end
  41. def future_offset(seconds)
  42. [
  43. [MIN_EXPIRATION, seconds.to_i].max,
  44. MAX_EXPIRATION,
  45. ].min
  46. end
  47. def set_min_expiration
  48. self.lease_seconds = 0 unless expires_at
  49. end
  50. end