I need to share a database handle among a few Ruby scripts. I am using the DBI gem to connect to the database. Consider the following example
#a.rb
class A
require 'dbi'
def connect
if a database handle is already open return it
else create a new one and return it
end
end
#b.rb
class B
require 'a'
a = A.new
dbh = a.connect
#some database queries here
end
#c.rb
class C
require 'a'
a = A.new
dbh = a.connect #Here the database handle created by class B should be returned
end
I understand that class instance variables are the way to go to achieve the said goal. Can someone please provide some insight on this?
Does DBI have something similar to Log4r
class A
require 'log4r'
Log4r::Logger.new('SO') #create a new instance here
end
class B
require 'a'
Log4r::Logger['SO'] # get the existing instance here
end
Many thanks.
The following uses a Singleton to manage a hash of DBI handles. It will create a new handle for a given set of connect options (the args one would pass to DBI.connect) the first time a connect is requested with those options. Subsequent requests with the same options will get the already open handle.