CHANSHIGELOG

いろんなこと

ActiveRecord単体でMigration機能を使いたい

Railsを使わずにActiveRecordとその機能であるMigrationを使いたい。どうやって使うんだ?となり色々調べて、欲しいのができたのでメモ程度に残します。

最初に

Gemfileを用意する

./Gemfile

source 'https://rubygems.org'

git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }

gem 'dotenv'
gem 'activerecord'
gem 'mysql2'
gem 'rake'

=> 適宜インストールしていただく

秘密っぽい接続情報を.envファイルに持たせる

./.env

DATABASE_HOST=localhost
DATABASE_PORT=3306
DATABASE_NAME=db_name
DATABASE_USER=user_name
DATABASE_PASSWORD=password

そして.envファイルから読んだ値をymlで読みたい

production:
  adapter:  mysql2
  encoding: utf8
  charset: utf8mb4
  host: <%= ENV['DATABASE_HOST'] %>
  port: <%= ENV['DATABASE_PORT'] %>
  database: <%= ENV['DATABASE_NAME'] %>
  username: <%= ENV['DATABASE_USER'] %>
  password: <%= ENV['DATABASE_PASSWORD'] %>

migrationファイルたち

※ samples テーブルを作ってみます

% mkdir -p db/migration
% touch db/migration/20200127000000_create_sample_table.rb

内容を書いていく

db/migration/20200127000000_create_sample_table.rb ※ファイル名とクラス名は合わせる必要あり(snake_case to PascalCase)

class CreateSampleTable < ActiveRecord::Migration[6.0]
  def change
    create_table :samples do |t|
      t.string :name
      t.text :description
      t.timestamps
    end
  end
end

Database接続周りを書く

./chanshige/database.rb

require 'active_record'

module Chanshige
  class Database
    # establish connection
    def self.connection(config, env = 'production')
      ActiveRecord::Base.configurations = config
      ActiveRecord::Base.establish_connection env.to_sym
      ActiveRecord::Base.time_zone_aware_attributes = true
    end
  end
end

最初に大体呼び出しちゃうファイルを作る

./bootstrap.rb

BASE_DIR = __dir__
$LOAD_PATH.unshift File.expand_path('./lib', BASE_DIR)

require 'dotenv/load'
require 'erb'
require 'chanshige/database'

# db connection
config = YAML.safe_load(ERB.new(IO.read(File.expand_path('./config/database.yml', BASE_DIR))).result)
Chanshige::Database.connection config

Rakefileを書く

./Rakefile

require_relative 'bootstrap'

namespace :db do
  migration_context = ActiveRecord::MigrationContext.new(
      File.expand_path('./db/migration', BASE_DIR),
      ActiveRecord::SchemaMigration
  )

  desc "Migrate the database (option: VERSION=x)"
  task :migrate do
    migration_context.migrate ENV['VERSION'] ? ENV['VERSION'] : nil
  end

  desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)"
  task :rollback do
    migration_context.rollback ENV['STEPS'] ? ENV['STEPS'] : 1
  end

  desc "Retrieves the current schema version number"
  task :version do
    p ActiveRecord::Migration.current_version
  end
end

実行!

% bundle exec rake --tasks    
rake db:migrate   # Migrate the database (option: VERSION=x)
rake db:rollback  # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:version   # Retrieves the current schema version number

普段、お仕事などでrubyを書く機会があまりないので、違和感などあったら教えてください!
2020年ももっと面白く、楽しんでまいりましょう!また次回!