Pry Tips

Pry is a powerful tool for debugging ruby codes. It’s idea is brilliantly awesome. It’s source code is easy to read and understand. Pry is already an irreplaceable part of my dev. env.. Below I am going to share a bit how I tuned it, hope that is also interesting to you. This one is quite tricky so before moving on, please try Pry a while if you haven’t used it before.

Focus when Entering Session

Pry allows us to add hooks, block below will be executed every time entering Pry session. Add it into your ~/.pryrc and it will ask Tmux to select the window running Pry, and bring the terminal on top with wmctrl.

1
2
3
4
5
6
7
8
Pry.config.hooks.add_hook(:before_session, :focus) do
  _pane = ENV['TMUX_PANE']
  if _pane
    _wid = `tmux list-window -t main -F '\#{window_index} \#{window_id}' | grep '@#{ _pane[1..-1] }$'`.split(' ')[0]
    `tmux select-window -t main:#{_wid}`
  end
  `wmctrl -a "Main Tmux Session"`
end

As you can see, this is very specific for my env. (assuming a tmux has session named ‘main’ and is running under terminal with specific title). Please feel free to modify it to fit you.

Source Code Editing

In a Pry session, you can dynamically modify source codes with the edit command. Pry allows us to configure which editor to use. Do you remember how I open file in project-based vim using a custom launcher? We can apply it in Pry too.

1
2
3
Pry.config.editor = proc { |file, line|
  "xdg-open 'vim://#{file}:#{line}'"
}

Trigger Code Reload

After modifying a source file, we will want Pry to reload dynamically without restarting our application. The Pry.load method come in handy.

1
2
3
4
5
6
7
8
" call pry to reload the current file
" example: Pry.load "/home/loki/projects/loper/app.rb"
function! ReloadCurrentFileInPry()
  let path = expand("%:p")
  let sendcmd = "send-keys -t main '" . 'Pry.load "' . path . '"' . "' Enter"
  call system("tmux " . sendcmd)
endfunction
nnoremap <leader>pp :call ReloadCurrentFileInPry()<cr>

Now whenever you press <leader>pp in VIM, a Pry.load command will be sent to the current Tmux main session.

Plugins

There are 2 must-have plugins to me. Check their github page for details.

  1. pry-stack_explorer

    Powerful tool to travel inside call stacks. When error occurred, show-stack returns the detailed call stacks. Locate the possible method caused problem then up <#id> to go into the context and debug.

  2. pry-clipboard

    Copying commands into system clipboard, later on we can paste into our source codes.

Comments