LoginSignup
13
6

More than 3 years have passed since last update.

rails console環境下でスクリプトを実行をする。

Last updated at Posted at 2020-07-28

経緯

rails console環境下でbenchmarkを取りたい場面があった。rails console環境下で以下のように1行ずつ実行するのも手間で、ファイルのスクリプトを読み込む手法が個人的によかったので記録に残す。

Loading development environment (Rails 6.0.3.2)
[1] pry(main)> require 'benchmark'
=> false
[2] pry(main)> def benchmark(try_num:)
[2] pry(main)*   

手順

1、rails consoleコマンドをターミナル上で実行。

$ rails c
Loading development environment (Rails 6.0.3.2)
[1] pry(main)> 

2、load "[ファイル名]"でファイルに記載されたスクリプトを読み込んで実行することができる。
スクリプトが実行されるので、ファイル内に定義した変数やメソッドをコンソール上で利用できる。

[1] pry(main)> load "benchmark_script.rb"
=> true

ちなみに、benchmark_script.rb の中身としては以下の通り。オブジェクト型の配列のサイズが大きいregionsと小さいcountriesでsampleメソッドのパフォーマンスを分析する。rails console環境下であるので、railsアプリケーション内で定義したモデルなども利用できる。

benchmark_script.rb
def benchmark(try_num:)
  # SQL 出力制御をする。
  old_logger = ActiveRecord::Base.logger
  ActiveRecord::Base.logger = nil

  regions = Region.all
  countries = Country.all
  Benchmark.bm(10) do |x|
    x.report('region'){ try_num.times { regions.sample } }
    x.report('country'){ try_num.times { countries.sample } }
  end
  # SQL 出力抑制を元に戻す
  ActiveRecord::Base.logger = old_logger
  nil
end

3、benchmark_script.rbて定義したbenchmarkメソッドを実行。結果として、sampleメソッドは配列のサイズは速度に影響しないことがわかる。

[2] pry(main)> benchmark try_num:10000
                 user     system      total        real
region       0.003220   0.000101   0.003321 (  0.003317)
country      0.002791   0.000147   0.002938 (  0.002952)
=> nil

備考

Railsアプリケーション内の修正(モデル内コードを一部書き換えた etc..)があった場合には、その修正分を反映させるためにrails consoleを再起動しないといけない。その際には、以下のreload!コマンドが便利です。(今まで、exitしてからrails consoleを立ち上げていた・・・)

[11] pry(main)> reload!
Reloading...
=> true
[12] pry(main)> 
13
6
1

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
13
6