2012-03-03 207 views
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 

非常感謝。

回答

2

以下內容使用Singleton來管理DBI句柄的散列。它會爲第一次使用這些選項請求連接時,爲給定的一組連接選項(將傳遞給DBI.connect的參數)創建一個新的句柄。後續具有相同選項的請求將獲得已打開的句柄。

# there_can_be_only_one_dbh.rb 

require 'dbi' 
require 'singleton' 

class ThereCanBeOnlyOneDBH 
    include Singleton 

    DEFAULT_CONNECT_OPTIONS = ['dsn','user','pw'] 

    def connect(*options) 
    options = DEFAULT_CONNECT_OPTIONS unless options and !options.empty? 
    @handles ||= {} 
    @handles[options.join('|')] ||= DBI.connect(*options) 
    end 
end 

# b.rb 
require 'there_can_be_only_one_dbh' 

class B 
    def initialize(*dbi_connect_options) 
    @dbh = ThereCanBeOnlyOneDBH.instance.connect(*dbi_connect_options) 
    end 

    # methods which issue queries using @dbh 
end 

# c.rb 
require 'there_can_be_only_one_dbh' 

class C 
    def initialize(*dbi_connect_options) 
    @dbh = ThereCanBeOnlyOneDBH.instance.connect(*dbi_connect_options) 
    end 

    # other methods which issue queries using @dbh 
end 
+0

謝謝你,你的代碼工作得很好:-) – 2012-03-16 09:53:12