Sha256: 302e45a688df4de72c05f98bfe180cb5a2e56e5ec90d8c6d0cd0e6c72eb3da17

Contents?: true

Size: 1.21 KB

Versions: 8

Compression:

Stored size: 1.21 KB

Contents

module PandaPal
  module OrganizationConcerns
    module TenantHandling
      extend ActiveSupport::Concern

      class_methods do
        def current
          find_by_name(Apartment::Tenant.current)
        end
      end

      included do
        after_create :create_schema
        after_commit :destroy_schema, on: :destroy

        before_validation on: [:update] do
          errors.add(:name, 'should not be changed after creation') if name_changed?
        end
      end

      def tenant_name
        name
      end

      def switch_tenant(&block)
        if block_given?
          Apartment::Tenant.switch(tenant_name, &block)
        else
          Apartment::Tenant.switch!(tenant_name)
        end
      end

      def rename!(new_name)
        do_switch = Apartment::Tenant.current == name
        ActiveRecord::Base.connection.execute(
          "ALTER SCHEMA \"#{name}\" RENAME TO \"#{new_name}\";"
        )
        self.class.where(id: id).update_all(name: new_name)
        reload
        switch_tenant if do_switch
      end

      private

      def create_schema
        Apartment::Tenant.create tenant_name
      end

      def destroy_schema
        Apartment::Tenant.drop tenant_name
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
panda_pal-5.12.7 app/models/panda_pal/organization_concerns/tenant_handling.rb
panda_pal-5.12.6 app/models/panda_pal/organization_concerns/tenant_handling.rb
panda_pal-5.12.5 app/models/panda_pal/organization_concerns/tenant_handling.rb
panda_pal-5.12.4 app/models/panda_pal/organization_concerns/tenant_handling.rb
panda_pal-5.12.3 app/models/panda_pal/organization_concerns/tenant_handling.rb
panda_pal-5.12.2 app/models/panda_pal/organization_concerns/tenant_handling.rb
panda_pal-5.12.1 app/models/panda_pal/organization_concerns/tenant_handling.rb
panda_pal-5.12.0 app/models/panda_pal/organization_concerns/tenant_handling.rb