This hash is the same one that is loaded from database.yml when using
Rails, so you could just pick up that file and load it:
require 'yaml' # Ruby standard library
ActiveRecord::Base.establish_connection(YAML.load_file('database.yml'))
If you are used to the features of edge Rails, you may not want to stick with the latest
gem version of ActiveRecord. To use the latest edge, first check out
ActiveRecord??™s trunk from Subversion:
$ svn co http://svn.rubyonrails.org/rails/trunk/activerecord \
vendor/activerecord
Then, just require the active_record.rb file from that directory:
require 'vendor/activerecord/lib/active_record'
Incorporating Rails Components | 285
ETL operations
ActiveRecord can be a useful tool to load data into and extract data from databases.
It can be used for anything from one-off migration scripts to hourly data transformation
jobs. The following is a representative example, using James Edward Gray II??™s
FasterCSV library:
require 'rubygems'
require 'fastercsv' # gem install fastercsv
require 'active_record'
# Set up AR connection and define User class
ActiveRecord::Base.establish_connection(
# (connection spec)...
)
class User
# The table we're importing into doesn't use Rails conventions,
# so we'll override some defaults.
set_table_name 'user'
set_primary_key 'userid'
end
FasterCSV.foreach('users.csv', :headers => true) do |row|
# The CSV header fields correspond to the database column names,
# so we can do this directly, with no mapping.
Pages:
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433