5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

binding.pryで条件付きでデバッグする

Posted at

what

Railsで binding.pryを使って、条件付きで処理を止める方法を知りたい。

Android Studioだとこれがデフォルトでできました。
例えば、何回もアクセスされるエンドポイントで、特定の条件のときにだけエラーが起きている場合、関係ないアクセスのときにも処理が止まってしまうとデバッグするのが面倒です。
(ある料理レシピサイトがあったとして、リストの3ページ目にアクセスしたときだけエラーが起きる場合。1ページめを表示したときにも処理が止まると面倒ですよね。)

how

まずは、 gemをインストール。

gem install pry-byebug

デバッグしたいファイルに以下を追加

require 'pry'

処理を止めたい箇所に以下を記述

binding.pry

さらに、処理を止めたい条件を以下のように記述

binding.pry if page == 3

これで page == 3のときにだけ処理が止まるようになりました。

おまけ

処理を止めた時に使えるコマンド

  • next
    • 次の行を実行(メソッドは実行される)
  • step
    • 次の行を実行、メソッドなら中に入る
  • continue
    • プログラムを実行し、pryを終了
  • break
    • break 数字=> 数字の行にbreak pointを貼る

aliasを貼る

以下を ~/.pryrcに貼り付ける

if defined?(PryByebug)
  Pry.commands.alias_command 'c', 'continue'
  Pry.commands.alias_command 's', 'step'
  Pry.commands.alias_command 'n', 'next'
  Pry.commands.alias_command 'f', 'finish'
end

直前のコマンドを Enterキーで繰り返す

以下を ~/.pryrcに貼り付ける

Pry::Commands.command /^$/, "repeat last command" do
  _pry_.run_command Pry.history.to_a.last
end
5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?