1
我需要在幾個Ruby腳本中共享數據庫句柄。我正在使用DBI gem連接到數據庫。考慮下面的例子共享數據庫句柄
#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
我明白,類實例變量是實現上述目標的方式。有人可以提供一些見解嗎?
DBI是否有類似的東西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
非常感謝。
謝謝你,你的代碼工作得很好:-) – 2012-03-16 09:53:12