Sha256: f1579dc8e953931f656f9cc06076f872f6ad6ea8da972a4ce75ef946df6dd7a4

Contents?: true

Size: 1.15 KB

Versions: 3

Compression:

Stored size: 1.15 KB

Contents

module Mongoid
  #
  # Tenancy Module
  #
  # Provides #tenant_key and #tenancy!
  #
  module Tenancy
    extend ActiveSupport::Concern
    #
    # Model instance
    module ClassMethods
      def tenant_key(key, options = {})
        field key, type: Symbol

        options[:validates] ||= { presence: true }
        options[:index] ||= {}

        validates key, { uniqueness: true }.merge(options[:validates])
        index({ key => 1 }, { unique: true }.merge(options[:index]))
        scope :active_tenants, -> { where(key.ne => nil) }

        define_method(:tenant_key) do
          send(key).to_s
        end

        define_singleton_method(:clear_tenancy!) do
          Thread.current[:tenancy] = nil
        end

        define_singleton_method(:with_tenants) do |&block|
          all.each do |t|
            t.tenancy!
            block.call(t)
          end
          clear_tenancy!
        end
      end

      def has_tenant(relative)
        define_method(relative) do
          tenancy! && relative.to_s.classify.constantize
        end
      end
    end

    def tenancy!
      Thread.current[:tenancy] = tenant_key
    end
  end # Tenancy
end # Mongoid

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mongoid-tenant-0.3.7 lib/mongoid/tenancy.rb
mongoid-tenant-0.3.5 lib/mongoid/tenancy.rb
mongoid-tenant-0.3.3 lib/mongoid/tenancy.rb