LoginSignup
2
2

More than 5 years have passed since last update.

Migration時のログを黙らせる

Last updated at Posted at 2014-07-09

発端

データベースを動的に作成するような某自作ツール。
通常使ってる分にはどちらでもいいが、テスト結果にDB作成のログが出るので黙らせたくなった。
ログレベル変えても効果なかったので調べようとしたが、中々マッチする記事に出会えなかった。
ので、メモを残しておく。

※公式ドキュメントに書いてあった...

結果

黙らせる前

$ ruby quiet_migrate_log.rb
-- create_table(:users)
   -> 0.2256s

黙らせた後

$ ruby quiet_migrate_log.rb

やりかた

rakeで黙らせる

$ rake db:migrate VERBOSE=false

実行ファイルで黙らせる

require 'active_record'

dbfilename = 'db/test.sqlite3'

ActiveRecord::Base.establish_connection(
  adapter:  'sqlite3',
  database: dbfilename
)
ActiveRecord::Base.connection

ActiveRecord::Migration.verbose = false
ActiveRecord::Migration.create_table :users do |t| 
  t.string  :name
  t.string  :email
  t.timestamp :created_at, :null => false
end

おまけ

マイグレーション時に他のことも喋らせたい場合

公式ドキュメントの同じ章に載っている通りなので詳細は省略するが、
sayやsay_with_time、suppress_messages等を使えば以下のようにログにメッセージを追加することができる

say_migrate_log.rb
require 'active_record'

dbfilename = 'db/say_migration.sqlite3'

ActiveRecord::Base.establish_connection(
  adapter:  'sqlite3',
  database: dbfilename
)
ActiveRecord::Base.connection

class MyMigration < ActiveRecord::Migration
  def create_users_table
    suppress_messages do
      create_table :users do |t| 
        t.string  :name
        t.string  :email
        t.timestamp :created_at, :null => false
      end 
    end

    say "Created Table"

    suppress_messages { add_index :users, :name }
    say "and an index!", true  #<= trueがあると字下げされる

    # ブロックの実行時間と共にメッセージを出力
    say_with_time 'With time' do
      sleep 3
    end 
  end 
end

MyMigration.new.create_users_table

実行結果

$ ruby say_migrate_log.rb
-- Created Table
   -> and an index!
-- With time
   -> 3.0001s
   -> 3 rows
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2