Dear all
I have the following ruby code that can establish multiple(around 300)
database connection and stored them in a hash (conn_pool).
I can use conn_pool[“Keys”].connection.execute(“select * from table”) to
get the SQL result.
My question is that, how can I initialize these database connections
when my rails project started? So I can access conn_pool[something] in
controllers.
Please give me some advices.
Thank you very much
Valentino
require ‘rubygems’
require ‘resolv’
require ‘activerecord’
class LIS_SSC_ST1 < ActiveRecord::Base
end
LIS_SSC_ST1.establish_connection(
:host => “localhost”,
:adapter => “jdbc”,
:dialect => “sybase”,
:autocommit => false,
:driver => “com.sybase.jdbc3.jdbc.SybDataSource”,
:url => “jdbc:sybase:Tds:cdcibm74.server.ha.org.hk:22601/SSC_DB”,
:username => “username”,
:password => “password”)
class Server < LIS_SSC_ST1
set_table_name “ssc_servers”
end
r = Regexp.new(“LIS_…_SP(1[012])”)
conn_pool = {}
def is_active?(dns,host)
Resolv.getaddress(dns) == Resolv.getaddress(host) ? true : false
end
def make_conn(h,server_name)
eval(“class #{server_name} < ActiveRecord::Base
end”)
eval(server_name).establish_connection(h)
end
Server.find(:all, :conditions => “server_type = ‘sybase’”, :order =>
“server_name”).each do |x|
if x.server_name =~ r
server_name = x.server_name.gsub(“SP”,“ST”)
server_dns = x.server_name.gsub(“SB","").gsub("”,"-").downcase
if is_active?(server_dns,x.server_host)
h = {:host => “localhost”,
:adapter => “jdbc”,
:dialect => “sybase”,
:autocommit => false,
:driver => “com.sybase.jdbc3.jdbc.SybDataSource”,
:url =>
“jdbc:sybase:Tds:#{server_dns}:#{x.port.to_s.gsub(/^4/,“2”)}/LAB_DB”,
:username => “username”,
:password => “password”}
conn_pool[server_name] = make_conn(h,server_name)
end
end
end