LoginSignup
51
42

More than 5 years have passed since last update.

今更ながらPryについて色々と調べてみた(前編)

Last updated at Posted at 2016-07-13

binding.pryはpry-byebugの機能でなく、pryの機能だった事すら知らなかったので。
思えばruby-debugで培った知識と人から伝え聞いた機能だけで何となく使って来てたな・・

前提

今回調べたバージョン&環境は以下の通り。

ruby (2.3.1)
rails (5.0.0)

pry (0.10.3)
pry-byebug (3.4.0)
pry-doc (0.9.0)
pry-rails (0.3.4)
byebug (9.0.5)

実践で利用する事の多い pry-byebugpry-railspry-doc の3つのGemも含めて調べました。

またフルパスで長いパスなどは「....」と省略しております。

そもそもPryって?

github:pry

上位版irbとも評されるRubyのコンソールツール。
irbと比較した時の利点としては、シンタックスハイライト、ドキュメントが充実、プラグインと組み合わせてデバックに利用できる、など。

Rubyの仕事をしたことがある人ならば、残念な環境でない限りは触った事があるはず。

Pryの機能

pry helpを見ると以下のカテゴライズされた機能があるらしい。
思った以上ボリュームが膨らんでしまったので前編・後編に分けました。

後編はコチラ

予め誤っておきますが、調べてもよくわからなかった機能があったのでいくつかスキップしてるのがあります。

=========== ここまで↑前編 ===========

  • Misc
  • Navigating pry
  • Prompts

以下はgemで追加された機能。

  • Rails
  • Byebug

補足的に.pryrcについても調べてみる。 

  • .pryrc

これらをざっと見てみることにする。

Context

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-backtrace      Show the backtrace for the pry session.
  raise-up           Raise an exception out of the current pry instance.
  reset              Reset the repl to a clean state.
  watch              Watch the value of an expression and print a notification whenever it changes.
  whereami           Show code surrounding the current context.
  wtf?               Show the backtrace of the most recent exception.

cd

カレントを指定したオブジェクト(インスタンス)に移動する。
移動後はpromtにオブジェクトが表示される。

# Stringオブジェクト
[1] pry(main)> cd String
[2] pry(String)>

# Timeインスタンス
[1] pry(main)> piyo = Time.now
[2] pry(main)> cd piyo
[3] pry(#<Time>):2>

find-method

指定したメソッドをカレントから検索する。
汎用的なメソッドを検索すると重いので、cdを利用して絞るといいです。
特に rails console などで汎用メソッドを検索すると激重になるので注意。

[1] pry(main)> find-method to_i

#<Class:0x007f903b834190>#to_io
#<Class:0x007f903b834190>#to_i

FileUtils.symbolic_modes_to_i

Pry::Terminal.screen_size_according_to_io_console
Complex
Complex#to_i
FileUtils
(以下略)

# cdで移動してから検索すると範囲を絞れる
[1] pry(main)> cd String
[2] pry(String):1> find-method to_i
String
String#to_i

ls

カレントオブジェクト(インスタンス)の値やメソッドを表示する。

[1] pry(main)> cd String
[2] pry(String):1> ls
constants: BLANK_RE
Object.methods: yaml_tag
JSON::Ext::Generator::GeneratorMethods::String::Extend#methods: json_create
String.methods: try_convert
String#methods:
  %                  b            chr            each_byte
(以下略)

# 結果が多い場合は-G(--grep)オプションを付けることで結果を絞ることが出来る
[3] pry(String):3> ls -G to_
String#methods:
  to_c  to_crlf  to_d  to_date  to_datetime  to_f  to_i  to_json  to_json_with_active_support_encoder  to_lf  to_nfc  to_nfd  to_nfkc  to_nfkd  to_r  to_s  to_str  to_sym  to_time

他のオプションは以下の通り。

-m, --methods               Show public methods defined on the Object
-M, --instance-methods      Show public methods defined in a Module or Class
-p, --ppp                   Show public, protected (in yellow) and private (in green) methods
-q, --quiet                 Show only methods defined on object.singleton_class and object.class
-v, --verbose               Show methods and constants on all super-classes (ignores Pry.config.ls.ceiling)
-g, --globals               Show global variables, including those builtin to Ruby (in cyan)
-l, --locals                Show hash of local vars, sorted by descending size
-c, --constants             Show constants, highlighting classes (in blue), and exceptions (in purple).
                                Constants that are pending autoload? are also shown (in yellow)
-i, --ivars                 Show instance variables (in blue) and class variables (in bright blue)
-G, --grep                  Filter output by regular expression
-h, --help                  Show this message.

pry-backtrace

現在のpry sessionのバックトレースを表示する。
そのためpry(pry-byebug)がバックトレース内に入る。

From: …./app/controllers/top_controller.rb @ line 5 TopController#index:

    2:   def index
    3:     @test = 1
    4: binding.pry
 => 5:     @test += 1
    6:   end

[1] pry(#<TopController>)> pry-backtrace
Backtrace:

..../vendor/bundle/ruby/2.3.0/gems/pry-byebug-3.4.0/lib/byebug/processors/pry_processor.rb:28:in `block in run'
..../vendor/bundle/ruby/2.3.0/gems/pry-byebug-3.4.0/lib/byebug/processors/pry_processor.rb:27:in `catch'
..../vendor/bundle/ruby/2.3.0/gems/pry-byebug-3.4.0/lib/byebug/processors/pry_processor.rb:27:in `run'
..../vendor/bundle/ruby/2.3.0/gems/pry-byebug-3.4.0/lib/byebug/processors/pry_processor.rb:111:in `resume_pry'
..../vendor/bundle/ruby/2.3.0/gems/pry-byebug-3.4.0/lib/byebug/processors/pry_processor.rb:63:in `at_line'
..../vendor/bundle/ruby/2.3.0/gems/byebug-9.0.5/lib/byebug/context.rb:96:in `at_line'
..../app/controllers/top_controller.rb:5:in `index'
(以下略)

# pry-byebugが入ってる場合は、backtraceの方がよさげ
[1] pry(#<TopController>)> backtrace
--> #0  TopController.index at …./app/controllers/top_controller.rb:5
    #1  ActionController::BasicImplicitRender.send_action(method#String, *args#Array) at …./vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0/lib/action_controller/metal/basic_implicit_render.rb:4
    #2  AbstractController::Base.process_action(action#NilClass, *args#Array) at …./vendor/bundle/ruby/2.3.0/gems/actionpack-5.0.0/lib/abstract_controller/base.rb:188
(以下略)

raise-up

pryインスタンスでExceptionを発生させる。
発生するエラーはRuntimeError。

[1] pry(main)> def test
[1] pry(main)*   begin
[1] pry(main)*     binding.pry
[1] pry(main)*     return true
[1] pry(main)*   rescue => e
[1] pry(main)*     return e.class
[1] pry(main)*   end
[1] pry(main)* end
=> :test
[2] pry(main)> test

From: (pry) @ line 3 Object#test:

    1: def test
    2:   begin
 => 3:     binding.pry
    4:     return true
    5:   rescue => e
    6:     return e.class
    7:   end
    8: end

[1] pry(main)> raise-up
=> RuntimeError

reset

pryインスタンス内で定義した情報などをクリアする。
railsアプリ実行中に叩くと止まるので注意。
純粋なrubyコードをテストしたい時用かな。

[1] pry(main)> hoge = 1
[2] pry(main)> p hoge
=> 1

[3] pry(main)> reset
Pry reset.
[4] pry(main)> p hoge
NameError: undefined local variable or method `hoge' for main:Object
from (pry):1:in `__pry__'

watch

指定した変数を監視し、変更があったら教えてくれる。

[1] pry(main)> hoge = %w(a b c b a)
=> ["a", "b", "c", "b", "a"]
[2] pry(main)> watch hoge
Watching hoge
watch: hoge => ["a", "b", "c", "b", "a"]

# 非破壊的メソッドで呼ばれても何も起きない
[3] pry(main)> hoge.uniq
=> ["a", "b", "c"]

# 破壊的メソッドを呼び出すと教えてくれる
[4] pry(main)> hoge.uniq!
watch: hoge => ["a", "b", "c"]
=> ["a", "b", "c"]

# -l(--list)オプションで監視中の一覧を表示する
[5] pry(main)> watch -l
Listing all watched expressions:

1: hoge => ["a", "b", "c", "b", "a"]

# -d(—delete)オプションで監視対象から外せる
[6] pry(main)> watch -d hoge
Deleting watch expression #0: hoge => ["a", "b", "c", "b", "a"]

whereami

カレントコンテキストの周辺コードを表示する。
「@」でaliasが貼ってあるのでそれで呼び出すことも可能。

From: …./app/controllers/top_controller.rb @ line 5 TopController#index:

    2:   def index
    3:     @test = 1
    4: binding.pry
 => 5:     @test += 1
    6:   end

[1] pry(#<TopController>)> hoge = 'aaa'

(中略)

# コンテキストを動かしてなければ再表示できる
[12] pry(#<TopController>)> @

From: …./app/controllers/top_controller.rb @ line 5 TopController#index:

    2:   def index
    3:     @test = 1
    4: binding.pry
 => 5:     @test += 1
    6:   end

wtf?

直前に起きたExceptionのbacktraceを表示してくれる。
backtraceの表示は10行ですが、‘?’の前に’!’を付けるとつけた分だけ表示してくれるというよくわからない仕様。

[1] pry(main)> hoge
NameError: undefined local variable or method `hoge' for main:Object
from (pry):1:in `__pry__'

# defaultで表示されるbacktraceは10行まで
[2] pry(main)> wtf?
Exception: NameError: undefined local variable or method `hoge' for main:Object
--
0: (pry):1:in `__pry__'
1: …./global/gems/pry-0.10.3/lib/pry/pry_instance.rb:355:in `eval'
2: …./global/gems/pry-0.10.3/lib/pry/pry_instance.rb:355:in `evaluate_ruby'

(中略)

9: …./global/gems/pry-0.10.3/lib/pry/repl.rb:77:in `block in repl'

# ‘?’の前に’!’を付けると1つにつき10行増えるというよくわからん仕様
[3] pry(main)> wtf!!?
Exception: NameError: undefined local variable or method `hoge' for main:Object
--
0: (pry):1:in `__pry__'
1: …./global/gems/pry-0.10.3/lib/pry/pry_instance.rb:355:in `eval'
2: …./global/gems/pry-0.10.3/lib/pry/pry_instance.rb:355:in `evaluate_ruby'

(中略)

24: …./global/bin/pry:23:in `<main>'

# -v(—verbose)オプションでbacktraceを全部見れる
[4] pry(main)> wtf? -v
Exception: NameError: undefined local variable or method `hoge' for main:Object
--
0: (pry):1:in `__pry__'
1: …./global/gems/pry-0.10.3/lib/pry/pry_instance.rb:355:in `eval'
2: …./global/gems/pry-0.10.3/lib/pry/pry_instance.rb:355:in `evaluate_ruby'

(中略)

97: ….//vendor/bundle/ruby/2.3.0/gems/puma-3.4.0/lib/puma/thread_pool.rb:114:in `block in spawn_thread'

Editing

Editing
  /^\s*!\s*$/        Clear the input buffer.
  amend-line         Amend a line of input in multi-line mode.
  edit               Invoke the default editor on a file.
  hist               Show and replay readline history.
  play               Playback a string variable, method, line, or file as input.
  show-input         Show the contents of the input buffer for the current multi-line expression.

/^\s*!\s*$/

入力中のバッファを削除します。
※ 7/15 コメントの指摘を受けて修正

[1] pry(main)> def hoge
[1] pry(main)*   return "fuga"
[1] pry(main)*   !
Input buffer cleared!

amend-line

定義中にミスった行を修正できます。

[1] pry(main)> def hoge
[1] pry(main)*   return 1
[1] pry(main)*   amend-line 2 return 2
1: def hoge
2:   return 2
[1] pry(main)* end
=> :hoge
[2] pry(main)> hoge
=> 2

他にも以下の形式で削除や追記などを行えます。

amend-line 1 puts 'new'    # replace line 1
amend-line 1..4 !          # delete lines 1..4
amend-line 3 >puts 'bye'   # insert before line 3
amend-line puts 'appended' # no line number modifies immediately preceding line

edit

指定したファイルの作成、編集を行います。

From: …./app/controllers/top_controller.rb @ line 5 TopController#index:

    2:   def index
    3:     @test = 1
    4: binding.pry
 => 5:     @test += 1
    6:

[1] pry(#<TopController>)> edit app/controllers/top_controller.rb
# => エディタが立ち上がる。
# @test += 1 を @test += 2 に変更

[2] pry(#<TopController>)> @

From: …./app/controllers/top_controller.rb @ line 5 TopController#index:

    2:   def index
    3:     @test = 1
    4: binding.pry
 => 5:     @test += 2
    6:   end

editの指定はファイル名だけでなく、クラス名、メソッド名でも可能。
またオプションでカレントのファイルを開いたり、開いた時の行数を指定出来たりもする。

# ファイルの開き方
edit sample.rb                edit -p MyClass#my_method
edit sample.rb --line 105     edit MyClass
edit MyClass#my_method        edit --ex
edit --method                 edit --ex -p

# オプション
-e, --ex             Open the file that raised the most recent exception (_ex_.file)
-i, --in             Open a temporary file containing the Nth input expression. N may be a range (default: -1..-1)
-t, --temp           Open an empty temporary file
-l, --line           Jump to this line in the opened file
-n, --no-reload      Don't automatically reload the edited file
-c, --current        Open the current __FILE__ and at __LINE__ (as returned by `whereami`)
-r, --reload         Reload the edited code immediately (default for ruby files)
-p, --patch          Instead of editing the object's file, try to edit in a tempfile and apply as a monkey patch
-m, --method         Explicitly edit the _current_ method (when inside a method context).
-h, --help           Show this message.

hist

過去に実行したpryコマンドの履歴を表示してくれる。

[1] pry(main)> hoge = 1
[2] pry(main)> hoge += 2
[3] pry(main)> hist
1: hoge = 1
2: hoge += 2

オプションで表示箇所を変えたり絞り込んだりもできます。

-a, --all              Display all history
-H, --head             Display the first N items
-T, --tail             Display the last N items
-s, --show             Show the given range of lines
-G, --grep             Show lines matching the given pattern
-c, --clear            Clear the current session's history
-r, --replay           Replay a line or range of lines
    --save             Save history to a file
-e, --exclude-pry      Exclude Pry commands from the history
-n, --no-numbers       Omit line numbers
-h, --help             Show this message.

play

指定したメソッドやファイルの指定した行の処理を実行してくれます。

[1] pry(main)> def hoge
[1] pry(main)*   p 1
[1] pry(main)*   p 2
[1] pry(main)*   p 3
[1] pry(main)*   p 4
[1] pry(main)*   p 5
[1] pry(main)* end
=> :hoge
[2] pry(main)> play hoge -l 3
2

# 複数指定も可能
[3] pry(main)> play hoge -l 3..5
2
3
4

show-input

入力中のバッファの内容を表示して確認できます。

[1] pry(main)> def hoge
[1] pry(main)*   p 1
[1] pry(main)*   p 2
[1] pry(main)*   show-input
1: def hoge
2:   p 1
3:   p 2

Introspection

Introspection
  ri                 View ri documentation.
  show-doc           Show the documentation for a method or class.
  show-source        Show the source for a method or class.
  stat               View method information and set _file_ and _dir_ locals.

show-doc、show-sourceはpry-doc gemがインストールされていないと見れないものが多いので、インストールしておいた方がいいです。

未インストール時にコマンドを実行すると以下のエラーが出ます。

[1] pry(main)> show-doc Array#to_h
Error: Cannot locate this method: to_h. Try `gem-install pry-doc` to get access to Ruby Core documentation.

ri

irbのriコマンドと同様。指定したRubyドキュメントを確認できます。

[4] pry(main)> ri Array
Array < Object

------------------------------------------------------------------------------
Includes:
Enumerable (from ruby core)

(以下略)

show-doc

指定したクラス、メソッドのドキュメントを表示する。

[1] pry(main)> show-doc Array#to_h

From: array.c (C Method):
Owner: Array
Visibility: public
Signature: to_h()
Number of lines: 5

Returns the result of interpreting ary as an array of
<tt>[key, value]</tt> pairs.

   [[:foo, :bar], [1, 2]].to_h
     # => {:foo => :bar, 1 => 2}

# オプションを付けることで、親クラスのメソッドを参照したりライン番号を出したりも出来る
[2] pry(main)> show-doc -sl Array#to_h

From: enum.c (C Method):
Owner: Enumerable
Visibility: public
Signature: to_h(*arg1)
Number of lines: 5

1: Returns the result of interpreting enum as a list of
2: <tt>[key, value]</tt> pairs.
3:
4:    %i[hello world].each_with_index.to_h
5:      # => {:hello => 0, :world => 1}

他に以下のオプションがあります。

-s, --super             Select the 'super' method. Can be repeated to traverse the ancestors
-l, --line-numbers      Show line numbers
-b, --base-one          Show line numbers but start numbering at 1 (useful for `amend-line` and `play` commands)
-a, --all               Show all definitions and monkeypatches of the module/class
-h, --help              Show this message.

show-source

指定したクラス、メソッドのソースコードを表示する。

[3] pry(main)> show-source Hash#map

From: enum.c (C Method):
Owner: Enumerable
Visibility: public
Number of lines: 12

static VALUE
enum_collect(VALUE obj)
{
    VALUE ary;

    RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);

    ary = rb_ary_new();
    rb_block_call(obj, id_each, 0, 0, collect_i, ary);

    return ary;
}

独自に作ったクラス、メソッドも表示できます。

[1] pry(main)> show-source TopController#index

From: …./app/controllers/top_controller.rb @ line 2:
Owner: TopController
Visibility: public
Number of lines: 5

  def index
    @test = 1
binding.pry
    @test += 2
  end

show-docと同様にオプションで親クラスのメソッドを見たり、行番号を振ったりできます。

[11] pry(main)> show-source -sl Array#map

From: enum.c (C Method):
Owner: Enumerable
Visibility: public
Number of lines: 12

 1: static VALUE
 2: enum_collect(VALUE obj)
 3: {
 4:     VALUE ary;
 5:
 6:     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
 7:
 8:     ary = rb_ary_new();
 9:     rb_block_call(obj, id_each, 0, 0, collect_i, ary);
10:
11:     return ary;
12: }

他に以下のオプションがあります。

-e, --eval              evaluate the command's argument as a ruby expression and show the class its return value
-s, --super             Select the 'super' method. Can be repeated to traverse the ancestors
-l, --line-numbers      Show line numbers
-b, --base-one          Show line numbers but start numbering at 1 (useful for `amend-line` and `play` commands)
-a, --all               Show all definitions and monkeypatches of the module/class
-h, --help              Show this message.

stat

指定したメソッドの情報を表示します。

[1] pry(main)> stat String#to_i
Method Information:
--
Name: to_i
Alias: None.
Owner: String
Visibility: public
Type: Unbound
Arity: -1
Method Signature: to_i(*arg1)
Source Location: Not found.

# 自作メソッドも可能
[2] pry(main)> def hoge(n)
[2] pry(main)*   return n += 1
[2] pry(main)* end
=> :hoge
[3] pry(main)> stat hoge
Method Information:
--
Name: hoge
Alias: None.
Owner: Object
Visibility: public
Type: Bound
Arity: 1
Method Signature: hoge(n)
Source Location: (pry):1

show系コマンドと同様にオプションがあるが、こちらはイマイチ使い方がわからない・・・

-M, --instance-methods      Operate on instance methods.
-m, --methods               Operate on methods.
-s, --super                 Select the 'super' method. Can be repeated to traverse the ancestors.
-c, --context               Select object context to run under.
-h, --help                  Show this message.

Gems

Gems
  gem-cd             Change working directory to specified gem's directory.
  gem-install        Install a gem and refresh the gem cache.
  gem-list           List and search installed gems.
  gem-open           Opens the working directory of the gem in your editor.

gem-cd

指定したgemのディレクトリに移動します。
Contextのcdとは別物かな。

[1] pry(main)> gem-cd rake
~/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-10.4.2
[2] pry(main)> .pwd
~/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-10.4.2
[3] pry(main)> .ls
CONTRIBUTING.rdoc MIT-LICENSE       README.rdoc       bin               lib               test
History.rdoc      Manifest.txt      Rakefile          doc               rakelib

gem-install

実行するとエラーになるんだが・・・バグ?
issueは特に上がってないけどなぁ。

[1] pry(main)> gem-install pry-byebug
NoMethodError: undefined method `split' for nil:NilClass
from ~/.rbenv/versions/2.3.1/gemsets/global/gems/pry-0.10.3/lib/pry/rubygem.rb:60:in `install'

# 記述は間違ってないと思うが・・・
[2] pry(main)> gem-install --help
Usage: gem-install GEM_NAME
Installs the given gem, refreshes the gem cache, and requires the gem for you
based on a best guess from the gem name.
gem-install pry-stack_explorer
    -h, --help      Show this message.

gem-list

インストール済のgem一覧を表示します。
gem listと同じかな。

[1] pry(main)> gem-list
bigdecimal (1.2.8)
builder (3.2.2)
bundle (0.0.1)

(中略)

# rails/consoleで叩くとbundlerで入れたgemも取れます(pry-railsが必要)
% bin/rails c
Loading development environment (Rails 4.2.6)
[1] pry(main)> gem-list

(中略)

mail (2.6.4)
actionmailer (4.2.6)
activemodel (4.2.6)
arel (6.0.3)
activerecord (4.2.6)

(中略)

gem-open

これも動かない・・
こっちはぽいのがissueに上がってるからバグなのかな?
https://github.com/pry/pry/issues/1533

[1] pry(main)> gem-open pry-doc
NoMethodError: undefined method `invoke_editor' for Pry::Editor:Class
from ~/.rbenv/versions/2.3.1/gemsets/global/gems/pry-0.10.3/lib/pry/commands/gem_open.rb:19:in `block in process'

Command

Commands
  import-set         Import a pry command set.
  install-command    Install a disabled command.

調べたけどよくわからなかったのでスキップ。
おそらく独自コマンドを作成するために使うと思うんだけど・・・

Gem系コマンドと組み合わせて使うのかな・・・
PryCommandSetRegistry

Aliases

Aliases
  !!!                Alias for `exit-program`
  !!@                Alias for `exit-all`
  $                  Alias for `show-source`
  ?                  Alias for `show-doc`
  @                  Alias for `whereami`
  clipit             Alias for `gist --clip`
  file-mode          Alias for `shell-mode`
  history            Alias for `hist`
  quit               Alias for `exit`
  quit-program       Alias for `exit-program`
  reload-method      Alias for `reload-code`
  show-method        Alias for `show-source`

Aliaseなので、各コマンドについての詳細はスキップ。

Input and output

Input and output
  .<shell command>   All text following a '.' is forwarded to the shell.
  cat                Show code from a file, pry's input buffer, or the last exception.
  change-inspector   Change the current inspector proc.
  change-prompt      Change the current prompt.
  fix-indent         Correct the indentation for contents of the input buffer
  list-inspectors    List the inspector procs available for use.
  list-prompts       List the prompts available for use.
  save-file          Export to a file using content from the repl.
  shell-mode         Toggle shell mode. bring in pwd prompt and file completion.

.<shell command>

先頭に「.」を付けるとシェルコマンドが実行できます。

[1] pry(main)> .ls
Gemfile      Gemfile~     Rakefile     bin          config.ru    lib          public       vendor
Gemfile.lock README.md    app          config       db           log          tmp

[2] pry(main)> .ls | grep Gem
Gemfile
Gemfile.lock
Gemfile~

cat

指定したファイルの中身を開くことが出来る。
シンタックスハイライトが効くので.catより見やすいか。

また以下の様なオプションを付けて開くことも可能。

--ex                Show the context of the last exception
-i, --in                Show one or more entries from Pry's expression history (default: -5..-1)
-s, --start             Starting line (defaults to the first line)
-e, --end               Ending line (defaults to the last line)
-l, --line-numbers      Show line numbers
-t, --type              The file type for syntax highlighting (e.g., 'ruby' or 'python')
-h, --help              Show this message.

change-inspector、list-inspectors

list-inspectorsで変更可能なinspector一覧を取得し、change-inspectorsで変更する。
inspectorはたぶんpryの出力方式かな。

[1] pry(main)> list-inspectors
Available inspectors
--
Name: default (selected)
The default Pry inspector. It has paging and color support, and uses
pretty_inspect when printing an object.

Name: simple
A simple inspector that uses #puts and #inspect when printing an
object. It has no pager, color, or pretty_inspect support.

Name: clipped
The clipped inspector has the same features as the 'simple' inspector
but prints large objects as a smaller string.

[2] pry(main)> change-inspector simple
Switched to the 'simple' inspector!

[3] pry(main)> list-inspectors
Available inspectors
--
Name: default
The default Pry inspector. It has paging and color support, and uses
pretty_inspect when printing an object.

Name: simple (selected)
A simple inspector that uses #puts and #inspect when printing an
object. It has no pager, color, or pretty_inspect support.

Name: clipped
The clipped inspector has the same features as the 'simple' inspector
but prints large objects as a smaller string.

change-prompt、list-prompts

list-promptsで変更可能なprompt一覧を取得し、change-promptで変更する。

[1] pry(main)> list-prompts
Available prompts
--
Name: default (selected)
The default Pry prompt. Includes information about the
current expression number, evaluation context, and nesting
level, plus a reminder that you're using Pry.

Name: simple
A simple '>>'.

Name: nav
A prompt that displays the binding stack as a path and
includes information about _in_ and _out_.

Name: none
Wave goodbye to the Pry prompt.

[2] pry(main)> change-prompt simple
>> change-prompt nav
[4] (pry) main: 0> change-prompt none
change-prompt default
[6] pry(main)>

違いが微妙すぎてよくわからん・・

promptは.pryrcでも設定できるみたいだけど、こっちの方が便利そう。
http://qiita.com/okuramasafumi/items/900286cd4f07c1bbbb5d

fix-indent

入力バッファのインデントを修正するとヘルプには書いてあるけど、違いがわからんのでスキップ。

save-file

入力バッファの内容をファイルに出力する事ができる。

[1] pry(main)> def hoge
[1] pry(main)*   puts ‘piyo'
[1] pry(main)* end
=> :hoge
[1] pry(main)> hoge
piyo
[4] pry(main)> save-file hoge --to hoge.rb
hoge.rb successfully saved
[5] pry(main)> .ls | grep hoge
hoge.rb

オプションで保存する行数とか指定できるみたいです。

[1] pry(main)> save-file -h
Usage: save-file [OPTIONS] --to [FILE]

Export to a file using content from the REPL.

save-file my_method --to hello.rb
save-file -i 1..10 --to hello.rb --append
save-file show-method --to my_command.rb
save-file sample_file.rb --lines 2..10 --to output_file.rb

-l, --lines       Restrict to a subset of lines. Takes a line number or range (default: 1..-1)
-o, --out         Select lines from Pry's output result history. Takes an index or range (default: -5..-1)
-i, --in          Select lines from Pry's input expression history. Takes an index or range (default: -5..-1)
-s, --super       Select the 'super' method. Can be repeated to traverse the ancestors
-d, --doc         Select lines from the code object's documentation
    --to          Specify the output file path
-a, --append      Append output to file
-h, --help        Show this message.

shell-mode

shell-modeの切替えを行う。
shell-modeだとpromptにディレクトリパスが表示されるようになり、ファイルなどの入力補完が有効になる・・・らしいが、自分の環境だと入力補完はうまく動かなかった。
promptは確認できたけど、設定の問題なのかなぁ・・

[1] pry(main)> shell-mode
pry main: …./app_sample $

pry main: …./app_sample $ shell-mode
[3] pry(main)>

後編はコチラ

参考にさせて頂いたサイト一覧

公式(github)のREADMEやwiki以外で参考にさせて頂いたサイトです。

51
42
2

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
51
42