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.

45 lines
1.0 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: invites
  5. #
  6. # id :integer not null, primary key
  7. # user_id :integer
  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. #
  15. class Invite < ApplicationRecord
  16. belongs_to :user, required: true
  17. has_many :users, inverse_of: :invite
  18. before_validation :set_code
  19. attr_reader :expires_in
  20. def expires_in=(interval)
  21. self.expires_at = interval.to_i.seconds.from_now unless interval.blank?
  22. @expires_in = interval
  23. end
  24. def valid_for_use?
  25. (max_uses.nil? || uses < max_uses) && (expires_at.nil? || expires_at >= Time.now.utc)
  26. end
  27. def expire!
  28. touch(:expires_at)
  29. end
  30. private
  31. def set_code
  32. loop do
  33. self.code = ([*('a'..'z'), *('A'..'Z'), *('0'..'9')] - %w(0 1 I l O)).sample(8).join
  34. break if Invite.find_by(code: code).nil?
  35. end
  36. end
  37. end