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.

42 lines
1.1 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. # comment :text
  16. #
  17. class Invite < ApplicationRecord
  18. include Expireable
  19. belongs_to :user, inverse_of: :invites
  20. has_many :users, inverse_of: :invite
  21. scope :available, -> { where(expires_at: nil).or(where('expires_at >= ?', Time.now.utc)) }
  22. validates :comment, length: { maximum: 420 }
  23. before_validation :set_code
  24. def valid_for_use?
  25. (max_uses.nil? || uses < max_uses) && !expired? && !(user.nil? || user.disabled?)
  26. end
  27. private
  28. def set_code
  29. loop do
  30. self.code = ([*('a'..'z'), *('A'..'Z'), *('0'..'9')] - %w(0 1 I l O)).sample(8).join
  31. break if Invite.find_by(code: code).nil?
  32. end
  33. end
  34. end