Skip to content

Instantly share code, notes, and snippets.

@eltercero
Last active June 1, 2020 14:39
Show Gist options
  • Save eltercero/3240b846dcc516d54f260e4c120354c0 to your computer and use it in GitHub Desktop.
Save eltercero/3240b846dcc516d54f260e4c120354c0 to your computer and use it in GitHub Desktop.

pry 101

wiki (documentation and many of tutorials)

basics

The gem is called pry. If pry-rails is also installed, pry will replace irb in rails console. It will also add some commands such as show-models or show-routes. More info on pry-rails here.

binding.pry will add a breakpoint in the code.

exit will resume the execution. You can interrupt the execution and leave it with !!!.

help is available by its own or with another command.

commands

  • ls: It will show all methods, variables and constants available to pry. You can scope the search by adding an object. i.e. ls User will list class/instance methods, variables, constants, etc. availables to the class. ls has a lot of options in case you need to be more specific:
> ls         # All

> ls -m      # Methods
> ls -M      # Instance methods

> ls -g      # Globals
> ls -l      # Local vars
> ls -c      # Constants

> ls -i      # Instance vars

> ls -G xx   # Grey by regex
  • cd: Change the current execution context to another object. i.e., being user an instance of User, you may use cd user to be under the user scope. After that you can directly access user methods and variables without the need to prepend user. to everything. This is handy for debugging, when you find that the breakpoint is not where the bug is apparently ocurring and you need to move to another context to, for instance, override methods or variables. You can user cd .., cd - or exitto go back.

  • show-source: Show the source where the current breakpoint is. You can also pass another method/class. i.e. show-source User#full_name.

  • edit: It will open the last command on the editor defined by $EDITOR. After saving and closing it will run it in pry.

  • hist: list the previous commands. You can also replay a range of last commands. More info with help hist

exceptions

Pry will store the last exception in _ex_. fun fact: you can use wtf? to see the backtrace. The more exclamation and interrogation you add, the longer the backtrace (you can access all of it with _ex_.backtrace; arguably more useful but less fun). More info about exceptions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment