How to build an ActiveRecord Adapter — Part 1 – Initialization

datePosted on 14:54, September 10th, 2009 by Peter Fitzgibbons

In this chapter, I’ll discuss the adapter initialization; how Rails 2.x reads from database.yml and launches the database initialization.

Rails Boot

Here is a condensation of the Rails boot process from Rails Guts.  As Mike Gunderloy suggests, it will be really helpful to have a blank rails app open with

 rake gems:freeze 

invoked :

  1. script/server (vendor/rails/railties/lib/commands/server.rb) requires environment.rb from the local path (./)
  2. in environment.rb
     Rails::Initializer.run do |config| 
  3. Initializer.run has a default parameter
     configuration = Configuration.new 

    (that’s Rails::Configuration in railties/lib/initializer.rb)

  4. Configuration#initialize is long, including
     self.database_configuration_file = default_database_configuration_file 
  5. Configuration#default_database_configuration_file is :
    def default_database_configuration_file
     File.join(root_path, 'config', 'database.yml')
     end
    
  6. Notice that the default command on Rails::Initializer#run was :process, so Initializer#process is now called, which includes #initialize_database …
    def initialize_database
     if configuration.frameworks.include?(:active_record)
     ActiveRecord::Base.configurations = configuration.database_configuration
     ActiveRecord::Base.establish_connection
     end
     end
    
    1. Configuration#database_configuration is where the database.yml is loaded and returned to ActiveRecord::Base.configurations :
      def database_configuration
       require 'erb'
       YAML::load(ERB.new(IO.read(database_configuration_file)).result)
       end
      
  7. Now were getting somewhere!!  AR::Base#establish_connection(nil) :
    1. because the call is with spec = nil, #establish_connection is re-executed with RAILS_ENV
    2. this time through, spec = RAILS_ENV (ie, :development), so #establish_connection is called again, this time with the database.yml hash-key of RAILS_ENV (from Configuration#database_configuration)
    3. 3rd time’s a charm!  Now, with spec set to config hash, require the adapter gem,
       gem "activerecord-#{spec[:adapter]}-adapter" 

      and execute the adapter-method (which is expected to be def’d from the adapter’s gem) :

       adapter_method = "#{spec[:adapter]}_connection" 

The adapter-method is the entry-point of our new adapter, so in my next post I’ll pick-apart the #establish_connection process and prepare for our multi-connection pooling adapter’s version.



categoryPosted in Uncategorized
Related Posts:

Leave a Reply

Name: (required)
Email: (required) (will not be published)
Website:
Comment: