• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

pry: Pry,一个用于Ruby的强大的可替代标准 IRB shell 的工具,也是运行时开发者控制 ...

原作者: [db:作者] 来自: 网络 收藏 邀请

Pry

Pry Build StatusCircle Build StatusCode ClimateGem VersionDocumentation StatusDownloads

Pry logo

© John Mair (banisterfiend) 2018
(Creator)

© Kyrylo Silin (kyrylosilin) 2018
(Maintainer)

Alumni:

  • Conrad Irwin
  • Ryan Fitzgerald
  • Robert Gleeson

Links:

Table of Contents

Introduction

Pry is a runtime developer console and IRB alternative with powerfulintrospection capabilities. Pry aims to be more than an IRB replacement. It isan attempt to bring REPL driven programming to the Ruby language.

Key features

  • Source code browsing (including core C source with the pry-doc gem)
  • Documentation browsing
  • Live help system
  • Open methods in editors (edit Class#method)
  • Syntax highlighting
  • Command shell integration (start editors, run git, and rake from within Pry)
  • Gist integration
  • Navigation around state (cd, ls and friends)
  • Runtime invocation (use Pry as a developer console or debugger)
  • Exotic object support (BasicObject instances, IClasses, ...)
  • A powerful and flexible command system
  • Ability to view and replay history
  • Many convenience commands inspired by IPython, Smalltalk and other advancedREPLs
  • A wide-range number ofplugins that provideremote sessions, full debugging functionality, and more.

Installation

Bundler

gem 'pry', '~> 0.13.1'

Manual

gem install pry

Overview

Pry is fairly flexible and allows significant usercustomization.It is trivial to read from any object that has a readline method andwrite to any object that has a puts method. Many other aspects of Pry arealso configurable, making it a good choice for implementing custom shells.

Pry comes with an executable so it can be invoked at the command line. Justenter pry to start. A pryrc file in $XDG_CONFIG_HOME/pry/ or the user'shome directory will be loaded if it exists. Type pry --help at the commandline for more information.

Commands

Nearly every piece of functionality in a Pry session is implemented as acommand. Commands are not methods and must start at the beginning of a line,with no whitespace in between. Commands support a flexible syntax and allow'options' in the same way as shell commands, for example the following Prycommand will show a list of all private instance methods (in scope) that beginwith 'pa'

pry(YARD::Parser::SourceParser):5> ls -Mp --grep ^paYARD::Parser::SourceParser#methods: parse  parser_class  parser_type  parser_type=  parser_type_for_filename

Navigating around state

Pry allows us to pop in and out of different scopes (objects) using the cdcommand. This enables us to explore the run-time view of a program orlibrary. To view which variables and methods are available within a particularscope we use the versatile lscommand.

Here we will begin Pry at top-level, then Pry on a class and then on an instancevariable inside that class:

pry(main)> class Hellopry(main)*   @x = 20pry(main)* end=> 20pry(main)> cd Hellopry(Hello):1> ls -iinstance variables: @xpry(Hello):1> cd @xpry(20):2> self + 10=> 30pry(20):2> cd ..pry(Hello):1> cd ..pry(main)> cd ..

The number after the : in the pry prompt indicates the nesting level. Todisplay more information about nesting, use the nesting command. E.g

pry("friend"):3> nestingNesting status:0. main (Pry top level)1. Hello2. 1003. "friend"=> nil

We can then jump back to any of the previous nesting levels by using thejump-to command:

pry("friend"):3> jump-to 1=> 100pry(Hello):1>

Runtime invocation

Pry can be invoked in the middle of a running program. It opens a Pry session atthe point it's called and makes all program state at that point available. Itcan be invoked on any object using the my_object.pry syntax or on the currentbinding (or any binding) using binding.pry. The Pry session will then beginwithin the scope of the object (or binding). When the session ends the programcontinues with any modifications you made to it.

This functionality can be used for such things as: debugging, implementingdeveloper consoles and applying hot patches.

code:

# test.rbrequire 'pry'class A  def hello() puts "hello world!" endenda = A.new# start a REPL sessionbinding.pry# program resumes here (after pry session)puts "program resumes here."

Pry session:

pry(main)> a.hellohello world!=> nilpry(main)> def a.goodbyepry(main)*   puts "goodbye cruel world!"pry(main)* end=> :goodbyepry(main)> a.goodbyegoodbye cruel world!=> nilpry(main)> exitprogram resumes here.

Command Shell Integration

A line of input that begins with a '.' will be forwarded to the commandshell. This enables us to navigate the file system, spawn editors, and run gitand rake directly from within Pry.

Further, we can use the shell-mode command to incorporate the present workingdirectory into the Pry prompt and bring in (limited at this stage, sorry) filename completion. We can also interpolate Ruby code directly into the shell byusing the normal #{} string interpolation syntax.

In the code below we're going to switch to shell-mode and edit the pryrcfile. We'll then cat its contents and reload the file.

pry(main)> shell-modepry main:/home/john/ruby/projects/pry $ .cd ~pry main:/home/john $ .emacsclient .pryrcpry main:/home/john $ .cat .pryrcdef hello_world  puts "hello world!"endpry main:/home/john $ load ".pryrc"=> truepry main:/home/john $ hello_worldhello world!

We can also interpolate Ruby code into the shell. In the example below we usethe shell command cat on a random file from the current directory and countthe number of lines in that file with wc:

pry main:/home/john $ .cat #{Dir['*.*'].sample} | wc -l44

Code Browsing

You can browse method source code with the show-source command. Nearly allRuby methods (and some C methods, with the pry-doc gem) can have their sourceviewed. Code that is longer than a page is sent through a pager (such as less),and all code is properly syntax highlighted (even C code).

The show-source command accepts two syntaxes, the typical ri Class#methodsyntax and also simply the name of a method that's in scope. You can optionallypass the -l option to show-source to include line numbers in the output.

In the following example we will enter the Pry class, list the instancemethods beginning with 'se' and display the source code for the set_last_result method:

pry(main)> cd Prypry(Pry):1> ls -M --grep sePry#methods: raise_up  raise_up!  raise_up_common  reset_eval_string  select_prompt  set_last_resultpry(Pry):1> show-source set_last_result -lFrom: /home/john/ruby/projects/pry/lib/pry/pry_instance.rb:405:Owner: PryVisibility: publicSignature: set_last_result(result, code=?)Number of lines: 6405: def set_last_result(result, code = "")406:   @last_result_is_exception = false407:   @output_ring << result408:409:   self.last_result = result unless code =~ /\A\s*\z/410: end

Note that we can also view C methods (from Ruby Core) using thepry-doc plugin; we also show off the alternate syntax forshow-source:

pry(main)> show-source Array#selectFrom: array.c in Ruby Core (C Method):Number of lines: 15static VALUErb_ary_select(VALUE ary){    VALUE result;    long i;    RETURN_ENUMERATOR(ary, 0, 0);    result = rb_ary_new2(RARRAY_LEN(ary));    for (i = 0; i < RARRAY_LEN(ary); i++) {        if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {            rb_ary_push(result, rb_ary_elt(ary, i));        }    }    return result;}

Documentation Browsing

One use-case for Pry is to explore a program at run-time by cd-ing in and outof objects and viewing and invoking methods. In the course of exploring it maybe useful to read the documentation for a specific method that you comeacross. show-source command supports two syntaxes - thenormal ri syntax as well as accepting the name of any method that is currentlyin scope.

The Pry documentation system does not rely on pre-generated rdoc or ri,instead it grabs the comments directly above the method on demand. This resultsin speedier documentation retrieval and allows the Pry system to retrievedocumentation for methods that would not be picked up by rdoc. Pry also has abasic understanding of both the rdoc and yard formats and will attempt to syntaxhighlight the documentation appropriately.

Nonetheless, the ri functionality is very good and has an advantage over Pry'ssystem in that it allows documentation lookup for classes as well asmethods. Pry therefore has good integration with ri through the ricommand. The syntax for the command is exactly as it would be in command-line -so it is not necessary to quote strings.

In our example we will enter the Gem class and view the documentation for thetry_activate method:

pry(main)> cd Gempry(Gem):1> show-source try_activate -dFrom: /Users/john/rbenv/versions/2.7.1/lib/ruby/2.7.0/rubygems.rb:194:Owner: #<Class:Gem>Visibility: publicSignature: try_activate(path)Number of lines: 28Try to activate a gem containing path. Returns true ifactivation succeeded or wasn't needed because it was alreadyactivated. Returns false if it can't find the path in a gem.def self.try_activate(path)  # finds the _latest_ version... regardless of loaded specs and their deps  # if another gem had a requirement that would mean we shouldn't  # activate the latest version, then either it would already be activated  # or if it was ambiguous (and thus unresolved) the code in our custom  # require will try to activate the more specific version.  spec = Gem::Specification.find_by_path pathpry(Gem):1>

We can also use ri in the normal way:

pry(main) ri Array#each----------------------------------------------------------- Array#each     array.each {|item| block }   ->   array------------------------------------------------------------------------     Calls _block_ once for each element in _self_, passing that element     as a parameter.        a = [ "a", "b", "c" ]        a.each {|x| print x, " -- " }     produces:        a -- b -- c --

Edit methods

You can use edit Class#method or edit my_method (if the method is in scope)to open a method for editing directly in your favorite editor. Pry has knowledgeof a few different editors and will attempt to open the file at the line themethod is defined.

You can set the editor to use by assigning to the Pry.editoraccessor. Pry.editor will default to $EDITOR or failing that will use nanoas the backup default. The file that is edited will be automatically reloadedafter exiting the editor - reloading can be suppressed by passing the--no-reload option to edit

In the example below we will set our default editor to "emacsclient" and openthe Pry#repl method for editing:

pry(main)> Pry.editor = "emacsclient"pry(main)> edit Pry#repl

Live Help System

Many other commands are available in Pry; to see the full list type help atthe prompt. A short description of each command is provided with basicinstructions for use; some commands have a more extensive help that can beaccessed via typing command_name --help. A command will typically say in itsdescription if the --help option is available.

Use Pry as your Rails Console

The recommended way to use Pry as your Rails console is to add the pry-railsgem to your Gemfile. This replaces thedefault console with Pry, in addition to loading the Rails console helpers andadding some useful Rails-specific commands.

If you don't want to change your Gemfile, you can still run a Pry console inyour app's environment using Pry's -r flag:

pry -r ./config/environment

Also check out thewikifor more information about integrating Pry with Rails.

Syntax Highlighting

Syntax highlighting is on by default in Pry. If you want to change the colors,check out the pry-theme gem.

You can toggle the syntax highlighting on and off in a session by using thetoggle-color command. Alternatively, you can turn it off permanently byputting the line Pry.color = false in your pryrc file.

Supported Rubies

  • CRuby >= 1.9.3
  • JRuby >= 1.7

Contact

In case you have a problem, question or a bug report, feel free to:

License

The project uses the MIT License. See LICENSE.md for details.

Contributors

Pry is primarily the work of John Mair (banisterfiend), for full listof contributors see thecontributors graph.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap