Extracting a connection out of ActiveRecord::Base

Hi

I’m trying to use the Typo wordpress converter script, but it requires
that the wordpress database is accessible over the connection to the
Typo database.

To get around this, I’m trying to use ActiveRecord::establish_connection
(…) to get a connection object to run the raw SQL queries that Typo’s
wordpress converter uses on. It doesn’t work with Ruby DBI, otherwise
I’d use that.

The problem I have is that when I do the following (this is not
inside an object inheriting from any of the ActiveRecord stuff):

self.connection = ActiveRecord::Base.connection
if self.options.include?(:db_adapter)
  typo_conn = ActiveRecord::Base.connection

  ActiveRecord::Base.establish_connection(
   :adapter  => self.options[:db_adapter],
   :host     => self.options[:db_host],
   :username => self.options[:db_username],
   :password => self.options[:db_password],
   :database => self.options[:wp_db]
   )
  self.connection = ActiveRecord::Base.connection

  ActiveRecord::Base.connection = typo_conn
  puts "connected."
end

the connection stored in self.connection seems to get closed when the
connection to the typo database is restored.

Is there some way to achieve the same effect (an ActiveRecord-style
connection object, going somewhere useful) without involving whatever
logic in ActiveRecord::Base.connection= shuts down the connection?

thanks

donald

On Tue, 20 Jun 2006 13:36:37 +1200
Donald G. [email protected] wrote:


the connection stored in self.connection seems to get closed when the
connection to the typo database is restored.

Is there some way to achieve the same effect (an ActiveRecord-style
connection object, going somewhere useful) without involving whatever
logic in ActiveRecord::Base.connection= shuts down the connection?

Why, yes there is!

self.connection = ActiveRecord::Base.connection
if self.options.include?(:db_adapter)
  typo_conn = ActiveRecord::Base.remove_connection
  ActiveRecord::Base.establish_connection(
   :adapter  => self.options[:db_adapter],
   :host     => self.options[:db_host],
   :username => self.options[:db_username],
   :password => self.options[:db_password],
   :database => self.options[:wp_db]
   )
  self.connection = ActiveRecord::Base.connection
  ActiveRecord::Base.establish_connection(typo_conn)
  self.connection.reconnect!                         <--------- aha!
  puts "connected."
end

donald

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs