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.

53 lines
1.3 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: invites
  5. #
  6. # id :bigint(8) not null, primary key
  7. # user_id :bigint(8) not null
  8. # code :string default(""), not null
  9. # expires_at :datetime
  10. # max_uses :integer
  11. # uses :integer default(0), not null
  12. # created_at :datetime not null
  13. # updated_at :datetime not null
  14. # autofollow :boolean default(FALSE), not null
  15. #
  16. class Invite < ApplicationRecord
  17. belongs_to :user
  18. has_many :users, inverse_of: :invite
  19. scope :available, -> { where(expires_at: nil).or(where('expires_at >= ?', Time.now.utc)) }
  20. scope :expired, -> { where.not(expires_at: nil).where('expires_at < ?', Time.now.utc) }
  21. before_validation :set_code
  22. attr_reader :expires_in
  23. def expires_in=(interval)
  24. self.expires_at = interval.to_i.seconds.from_now unless interval.blank?
  25. @expires_in = interval
  26. end
  27. def valid_for_use?
  28. (max_uses.nil? || uses < max_uses) && !expired?
  29. end
  30. def expire!
  31. touch(:expires_at)
  32. end
  33. def expired?
  34. !expires_at.nil? && expires_at < Time.now.utc
  35. end
  36. private
  37. def set_code
  38. loop do
  39. self.code = ([*('a'..'z'), *('A'..'Z'), *('0'..'9')] - %w(0 1 I l O)).sample(8).join
  40. break if Invite.find_by(code: code).nil?
  41. end
  42. end
  43. end