2017-11-27 10:07:59 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: invites
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
2018-02-07 10:35:44 -05:00
|
|
|
# user_id :integer 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
|
|
|
|
#
|
|
|
|
|
|
|
|
class Invite < ApplicationRecord
|
2018-01-19 14:56:47 -05:00
|
|
|
belongs_to :user
|
2017-11-27 10:07:59 -05:00
|
|
|
has_many :users, inverse_of: :invite
|
|
|
|
|
2017-12-01 10:40:02 -05:00
|
|
|
scope :available, -> { where(expires_at: nil).or(where('expires_at >= ?', Time.now.utc)) }
|
|
|
|
scope :expired, -> { where.not(expires_at: nil).where('expires_at < ?', Time.now.utc) }
|
|
|
|
|
2017-11-27 10:07:59 -05:00
|
|
|
before_validation :set_code
|
|
|
|
|
|
|
|
attr_reader :expires_in
|
|
|
|
|
|
|
|
def expires_in=(interval)
|
|
|
|
self.expires_at = interval.to_i.seconds.from_now unless interval.blank?
|
|
|
|
@expires_in = interval
|
|
|
|
end
|
|
|
|
|
|
|
|
def valid_for_use?
|
2017-11-28 09:41:02 -05:00
|
|
|
(max_uses.nil? || uses < max_uses) && !expired?
|
2017-11-27 10:07:59 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def expire!
|
|
|
|
touch(:expires_at)
|
|
|
|
end
|
|
|
|
|
2017-11-28 09:41:02 -05:00
|
|
|
def expired?
|
|
|
|
!expires_at.nil? && expires_at < Time.now.utc
|
|
|
|
end
|
|
|
|
|
2017-11-27 10:07:59 -05:00
|
|
|
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
|