2012-03-03 122 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