2009年8月24日月曜日

[Rails][CodeReading] Rails::Initializer (11) initialize_database

Initializer.process で11番目に呼ばれる initialize_database メソッド。

def initialize_database
if configuration.frameworks.include?(:active_record)
ActiveRecord::Base.configurations = configuration.database_configuration
ActiveRecord::Base.establish_connection
end
end

Configuration.database_configuration は、config/database.yml を評価して返す。

def default_database_configuration_file
File.join(root_path, 'config', 'database.yml')
end

def database_configuration
require 'erb'
YAML::load(ERB.new(IO.read(database_configuration_file)).result)
end

ActiveRecord::Base.establish_connection は、ドキュメントによると
Establishes the connection to the database. Accepts a hash as input where the +:adapter+ key must be specified with the name of a database adapter (in lower-case) example for regular databases (MySQL, Postgresql, etc):
(データベースコネクションを確立する。引数に1つのハッシュを取る。引数のハッシュは、:adapterキーに紐付けられたデータベースアダプタ名(MySQL, Postgresql, など)を含んでいなければならない。)

とのこと。
# 初期化の時点でデータベースにつなぎに行くということ??

ActiveRecord::Base.establish_connection の実体は、activerecordの奥深くにありました。


# activerecord-2.3.3/lib/active_record/connection_adapters/abstract_adapter.rb
def self.establish_connection(spec = nil)
case spec
when nil
raise AdapterNotSpecified unless defined? RAILS_ENV
establish_connection(RAILS_ENV)
when ConnectionSpecification
@@connection_handler.establish_connection(name, spec)
when Symbol, String
if configuration = configurations[spec.to_s]
establish_connection(configuration)
else
raise AdapterNotSpecified, "#{spec} database is not configured"
end
else
spec = spec.symbolize_keys
unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end

begin
require 'rubygems'
gem "activerecord-#{spec[:adapter]}-adapter"
require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
rescue LoadError
begin
require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
rescue LoadError
raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{$!})"
end
end

adapter_method = "#{spec[:adapter]}_connection"
if !respond_to?(adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
end

remove_connection
establish_connection(ConnectionSpecification.new(spec, adapter_method))
end
end

たしかに、:adapterキーがなければ例外を投げている(spec.key?(:adapter) then raise AdapterNotSpecified)。
# このあたり、いつかきちんと読みたい。

[Rails][CodeReading] Railsの初期化コードを読む (イントロ&目次)

0 件のコメント:

コメントを投稿