logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

invite.rb (1280B)


  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: invites
  5. #
  6. # id :integer not null, primary key
  7. # user_id :integer 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. #
  15. class Invite < ApplicationRecord
  16. belongs_to :user
  17. has_many :users, inverse_of: :invite
  18. scope :available, -> { where(expires_at: nil).or(where('expires_at >= ?', Time.now.utc)) }
  19. scope :expired, -> { where.not(expires_at: nil).where('expires_at < ?', Time.now.utc) }
  20. before_validation :set_code
  21. attr_reader :expires_in
  22. def expires_in=(interval)
  23. self.expires_at = interval.to_i.seconds.from_now unless interval.blank?
  24. @expires_in = interval
  25. end
  26. def valid_for_use?
  27. (max_uses.nil? || uses < max_uses) && !expired?
  28. end
  29. def expire!
  30. touch(:expires_at)
  31. end
  32. def expired?
  33. !expires_at.nil? && expires_at < Time.now.utc
  34. end
  35. private
  36. def set_code
  37. loop do
  38. self.code = ([*('a'..'z'), *('A'..'Z'), *('0'..'9')] - %w(0 1 I l O)).sample(8).join
  39. break if Invite.find_by(code: code).nil?
  40. end
  41. end
  42. end