Method: DatabaseLoader.connect_as

Defined in:
lib/database_loader.rb

.connect_as(schema) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/database_loader.rb', line 85

def self.connect_as(schema)
  begin
    connection_config = ActiveRecord::Base.connection.raw_connection.instance_variable_get("@config").symbolize_keys
    connection_name = nil
    # When running rake test|spec RAILS_ENV is development by default,
    # so we need to guess config from current connection.
    ActiveRecord::Base.configurations.each do |name, config|
      # current configuration?
      if connection_config.symbolize_keys == config.symbolize_keys
        # current configuration has also _apps configuration?
        if ActiveRecord::Base.configurations.any? { |other_name, _| other_name.to_s == "#{name}_#{schema}" }
          connection_name = name
          break
        end
      end
    end
    if schema != :local
      unless connection_name
        raise "Missing database.yml configuration for <RAILS_ENV>_#{schema}."
      end
      puts "* Loading SQL statements in #{connection_name.downcase}_apps"
      ActiveRecord::Base.establish_connection("#{connection_name}_#{schema}".to_sym)
    end
    yield connection_config
  ensure
    if schema != :local
      # Set back the original connection
      ActiveRecord::Base.establish_connection(connection_name)
    end
  end
end