class ZoomUser < ApplicationRecord has_many :zoom_meetings, dependent: :nullify after_create :create_api_user, if: -> { api_id.nil? } before_destroy :abort_destroy scope :free, -> { where.not(id: ZoomMeeting.active.pluck(:zoom_user_id)) } def api_email self.class.api_email(self.id) end def create_api_user self.api_id = gateway.create_host(api_email) save end def delete_api_user gateway.delete_host(self.api_id) self.api_id = nil save end class << self def api_email(id) "host#{id}@directme" end end private def abort_destroy if api_id.present? errors.add(:base, "You can't destroy ZoomUser before explicitly deleting it through API.") throw(:abort) end end def gateway @gateway ||= ZoomGateway.new end end