Railsでなくとも使ってみる

RailsでARに慣れるとDBIなどでのアクセスはストレスです。
楽をしたい。
RailsじゃなくてもARを使いたい。
そこで使ってみました。今更ですが。
ちなみにActiveRecordはMITライセンスです。

CGIで使いたいなーという状況。
共用のレンタルサーバなんかでgemなんてあてにできません。
ここでは必要なファイルはすべてlib以下に入れておきます。

$ ls lib
active_record  active_record.rb  active_support  active_support.rb
$APPLICATION_ROOT = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift File.join($APPLICATION_ROOT, './lib')

# 接続
# MySQL
ActiveRecord::Base.establish_connection(:adapter => "mysql",
                                        :host => "localhost",
                                        :username => "user",
                                        :password => "password",
                                        :encoding => "utf8",
                                        :database => "db_test")
# PostgreSQL
ActiveRecord::Base.establish_connection(:adapter => "postgresql",
                                        :host => "localhost",
                                        :username => "user",
                                        :password => "password",
                                        :encoding => "utf8",
                                        :database => "db_test")
# SQLite3
# :dbfile => ':memory:'とすると実ファイルを作らずメモリ内で。
# 実行を終えると消えちゃう。テストに良さそう。
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3',
                                        :dbfile => 'db_file')

# あとはいつもどおりに
class User < ActiveRecord::Base
end

user = User.create(:name => 'lam')

Migrationを使いたい場合は、

require 'logger'
ActiveRecord::Base.logger = Logger.new(File.join($APPLICATION_ROOT, 'log/debug.log'))
# ActiveRecord::Base.logger.level = Logger::ERROR

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.column :name, :string, :nil => false
    end
  end
end

# Migration実行
CreateUsers.migrate(:up)

という風に。

また、Railsのように番号で管理して、希望のバージョンに戻したりいろいろしたいなら、

# migrate/001_create_boards.rb
class CreateBoards
  def self.up
    create_table :boards do |t|
      t.column :name, :string
    end
  end

  def self.down
    drop_table :boards
  end
end

# migrate/002_create_entries.rb
class CreateEntries
  def self.up
    create_table :entries do |t|
      t.column :title, :string
      t.column :body,  :string
    end
  end

  def self.down
    drop_table :entries
  end
end

# ActiveRecord::Migrator.migrate(
#   Migration用のコードのディレクトリ,
#   希望のバージョン。省略するかnilで最新)
ActiveRecord::Migrator.migrate("migrate", 2)

という具合。


ただ、生CGIで使うには頭の痛い問題もあって・・・

require 'benchmark'
Benchmark.bm do |x|
  x.report{ require 'active_record' }
  x.report {
    ActiveRecord::Base.establish_connection(
      :adapter => 'mysql',
      :host => 'localhsot',
      :username => 'root',
      :password => '',
      :encoding => 'utf8',
      :database => 'cookbook')
  }
end

で、

      user     system      total        real
  0.280000   0.700000   0.980000 (  1.142170)
  0.000000   0.000000   0.000000 (  0.000002)

requireだけでこれは・・・