Sha256: 9d171286b7d8aaa6d3adf78aa225e3a98d9a5f4c790c4e75fcae3fe08beb5581

Contents?: true

Size: 1.73 KB

Versions: 1

Compression:

Stored size: 1.73 KB

Contents

require 'active_support/core_ext/string/inflections'    # for `constantize`

module Apartment
	module Database
	  
	  MULTI_TENANT_METHODS = [:create, :switch, :reset, :connect_and_reset, :process]
	  
	  class << self

      # Call init to establish a connection to the public schema on all excluded models
      # This must be done before creating any new schemas or switching
  	  def init
  	    connect_exclusions
      end
      
      MULTI_TENANT_METHODS.each do |method|
        class_eval <<-RUBY
          def #{method}(*args, &block)
            adapter.send(:#{method}, *args, &block)
          end
        RUBY
      end
      
      def adapter
		    @adapter ||= begin
  		    adapter_method = "#{config[:adapter]}_adapter"
		    
  		    begin
            require "apartment/adapters/#{adapter_method}"
          rescue LoadError => e
            raise "The adapter `#{config[:adapter]}` is not yet supported"
          end

          unless respond_to?(adapter_method)
            raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter"
          end
        
          send(adapter_method, config)
        end
	    end
	    
	    def reload!
	      @adapter = nil
	      @config = nil
      end
      
  		private
  		
  		  def connect_exclusions
  		    # Establish a connection for each specific excluded model
          # Thus all other models will shared a connection (at ActiveRecord::Base) and we can modify at will
    	    Apartment.excluded_models.each do |excluded_model|
    				excluded_model.establish_connection config
    			end
        end
      
        def config
          @config ||= Rails.configuration.database_configuration[Rails.env].symbolize_keys
        end
    end
	    					
	end
	
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
apartment-0.6.0 lib/apartment/database.rb