Class: MultitenancyTools::SchemaSwitcher

Inherits:
Object
  • Object
show all
Defined in:
lib/multitenancy_tools/schema_switcher.rb

Overview

SchemaSwitcher can be used to switch between PostgreSQL schemas on a connection. It uses PostgreSQL search_path to achieve this functionality.

Instance Method Summary collapse

Constructor Details

#initialize(schema, connection = ActiveRecord::Base.connection) ⇒ SchemaSwitcher

Returns a new instance of SchemaSwitcher.

Parameters:

  • schema (String)

    schema name

  • connection (ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) (defaults to: ActiveRecord::Base.connection)

    connection adapter



7
8
9
10
# File 'lib/multitenancy_tools/schema_switcher.rb', line 7

def initialize(schema, connection = ActiveRecord::Base.connection)
  @connection = connection
  @schema = @connection.quote(schema)
end

Instance Method Details

#run(&block) ⇒ Object

This sets the connection search_path to use only the current schema, yields the block and then change search_path back to its previous value.



14
15
16
17
18
19
20
# File 'lib/multitenancy_tools/schema_switcher.rb', line 14

def run(&block)
  original_path = @connection.schema_search_path
  set_path_if_required(@schema)
  yield
ensure
  set_path_if_required(original_path)
end