2017-11-27 10:07:59 -05:00
|
|
|
# frozen_string_literal: true
|
2023-02-20 00:58:28 -05:00
|
|
|
|
2017-11-27 10:07:59 -05:00
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: invites
|
|
|
|
#
|
2018-04-23 05:29:17 -04:00
|
|
|
# id :bigint(8) not null, primary key
|
|
|
|
# user_id :bigint(8) not null
|
2017-11-27 10:07:59 -05: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 12:00:23 -04:00
|
|
|
# autofollow :boolean default(FALSE), not null
|
2019-08-19 05:40:42 -04:00
|
|
|
# comment :text
|
2017-11-27 10:07:59 -05:00
|
|
|
#
|
|
|
|
|
|
|
|
class Invite < ApplicationRecord
|
2018-06-29 09:34:36 -04:00
|
|
|
include Expireable
|
|
|
|
|
2019-07-26 12:55:33 -04:00
|
|
|
belongs_to :user, inverse_of: :invites
|
2023-12-01 10:52:47 -05:00
|
|
|
has_many :users, inverse_of: :invite, dependent: nil
|
2017-11-27 10:07:59 -05:00
|
|
|
|
2017-12-01 10:40:02 -05:00
|
|
|
scope :available, -> { where(expires_at: nil).or(where('expires_at >= ?', Time.now.utc)) }
|
|
|
|
|
2019-08-19 05:40:42 -04:00
|
|
|
validates :comment, length: { maximum: 420 }
|
|
|
|
|
2017-11-27 10:07:59 -05:00
|
|
|
before_validation :set_code
|
|
|
|
|
|
|
|
def valid_for_use?
|
2020-09-15 08:37:58 -04:00
|
|
|
(max_uses.nil? || uses < max_uses) && !expired? && user&.functional?
|
2017-11-27 10:07:59 -05: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
|