LoginSignup
7
8

More than 5 years have passed since last update.

rails開発をPry使用してデバックの効率化

Last updated at Posted at 2015-09-30

Pryを利用することで、rails consoleでコマンドを使用して対話型でデバックができて便利。
なので、使用方法をまとめておくことにしました。

Railsコンソールで利用できるようにする

GemfileにPryを追加する

  group :development, :test do
    gem 'pry-byebug'
    gem 'pry-rails'
  end

Bundlerでgemをインストールする

bundle install

Railsコンソールを開く

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

irbからpryに変わっている

Pryを使う

helpを打って打って利用可能なコマンドなどの説明を見る

$ rails c
Loading development environment (Rails 4.2.3)
[1] pry(main)> help
Help
  help               Show a list of commands or information about a specific command.

Context
  cd                 Move into a new context (object or scope).
  find-method        Recursively search for a method within a class/module or the current namespace.
  ls                 Show the list of vars and methods in the current scope.
・
・
・

pry-railsで追加されるコマンドの抜粋

コマンド 意味
recognize-path 引数に渡した文字列などルーティングのactionやcontroller情報にパースする
show-middleware 読み込んでいる Rake Middleware を表示する
show-model 引数で渡したモデルの情報を表示する
show-models すべてのモデルの情報を表示する
show-routes ルーティング情報を表示する

show-modelの実行例

[1] pry(main)> show-model User
User
  id: integer
  username: string
  email: string
  encrypted_password: string
  reset_password_token: string
  reset_password_sent_at: datetime
  remember_created_at: datetime
  sign_in_count: integer
  current_sign_in_at: datetime
  last_sign_in_at: datetime
  current_sign_in_ip: string
  last_sign_in_ip: string
  created_at: datetime
  updated_at: datetime
  has_many :user_work_groups

ステップ実行でデバック

pry-byebugをインストールしたことによって、デバッグ実行するが可能なっている

ソースコードの中にbinding.pryを記述することによって、ブレークポイントとなる。
binding.pryと入力していた行が実行された時にプログラムが中断されるようになる。

$ rails s
=> Booting WEBrick
=> Rails 4.2.3 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server

省略

    2: def index
    3:   @users = User.all
 => 4:   binding.pry
   5:   puts "test"
    6: end
[1] pry(#<UsersController>)> 

ステップ実行のコマンド

コマンド 意味
step メソッドの内部に入って1行進める
next 現在のメソッドのレイヤーで1行進める
finish 現在のメソッドを抜ける
continue デバッグを抜けてプログラムの実行を続ける
break ブレイクポイントを管理する

nextコマンド実行例

[1] pry(#<UsersController>)>  next
省略

    2: def index
    3:   @users = User.all
    4:   binding.pry
 => 5:   puts "test"
    6: end

7
8
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
7
8