invite.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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, dependent: nil
  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&.functional?
  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