2017-11-27 15:07:59 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: invites
|
|
|
|
#
|
2018-04-23 10:29:17 +01:00
|
|
|
# id :bigint(8) not null, primary key
|
|
|
|
# user_id :bigint(8) not null
|
2017-11-27 15:07:59 +00:00
|
|
|
# code :string default(""), not null
|
|
|
|
# expires_at :datetime
|
|
|
|
# max_uses :integer
|
|
|
|
# uses :integer default(0), not null
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
2018-06-15 17:00:23 +01:00
|
|
|
# autofollow :boolean default(FALSE), not null
|
2017-11-27 15:07:59 +00:00
|
|
|
#
|
|
|
|
|
|
|
|
class Invite < ApplicationRecord
|
2018-06-29 14:34:36 +01:00
|
|
|
include Expireable
|
|
|
|
|
2018-01-19 19:56:47 +00:00
|
|
|
belongs_to :user
|
2017-11-27 15:07:59 +00:00
|
|
|
has_many :users, inverse_of: :invite
|
|
|
|
|
2017-12-01 15:40:02 +00:00
|
|
|
scope :available, -> { where(expires_at: nil).or(where('expires_at >= ?', Time.now.utc)) }
|
|
|
|
|
2017-11-27 15:07:59 +00:00
|
|
|
before_validation :set_code
|
|
|
|
|
|
|
|
def valid_for_use?
|
2017-11-28 14:41:02 +00:00
|
|
|
(max_uses.nil? || uses < max_uses) && !expired?
|
2017-11-27 15:07:59 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def set_code
|
|
|
|
loop do
|
|
|
|
self.code = ([*('a'..'z'), *('A'..'Z'), *('0'..'9')] - %w(0 1 I l O)).sample(8).join
|
|
|
|
break if Invite.find_by(code: code).nil?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|