1
0

invite.rb 1.1 KB

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