The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

40 lines
984 B

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