在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Pry© John Mair (banisterfiend) 2018 © Kyrylo Silin (kyrylosilin) 2018 Alumni:
Links: Table of ContentsIntroductionPry 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
InstallationBundlergem 'pry', '~> 0.13.1' Manualgem install pry OverviewPry is fairly flexible and allows significant usercustomization.It is trivial to read from any object that has a Pry comes with an executable so it can be invoked at the command line. Justenter CommandsNearly 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 statePry allows us to pop in and out of different scopes (objects) using the 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 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 the pry("friend"):3> jump-to 1=> 100pry(Hello):1> Runtime invocationPry 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 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 IntegrationA 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 In the code below we're going to switch to 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 pry main:/home/john $ .cat #{Dir['*.*'].sample} | wc -l44 Code BrowsingYou can browse method source code with the The In the following example we will enter the 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 the 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 BrowsingOne use-case for Pry is to explore a program at run-time by The Pry documentation system does not rely on pre-generated Nonetheless, the In our example we will enter the 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 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 methodsYou can use You can set the editor to use by assigning to the In the example below we will set our default editor to "emacsclient" and openthe pry(main)> Pry.editor = "emacsclient"pry(main)> edit Pry#repl Live Help SystemMany other commands are available in Pry; to see the full list type Use Pry as your Rails ConsoleThe recommended way to use Pry as your Rails console is to add the If you don't want to change your Gemfile, you can still run a Pry console inyour app's environment using Pry's pry -r ./config/environment Also check out thewikifor more information about integrating Pry with Rails. Syntax HighlightingSyntax 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 the Supported Rubies
ContactIn case you have a problem, question or a bug report, feel free to:
LicenseThe project uses the MIT License. See LICENSE.md for details. ContributorsPry is primarily the work of John Mair (banisterfiend), for full listof contributors see thecontributors graph. |
请发表评论