pry上で小さなパーツを組み合わせるみたいな環境を作りたかった

rubyのString/Symbol -> pryのcommand というのは 以前 http://toqoz.hateblo.jp/entry/2013/01/17/103458 に書いた。
pryのcommand -> rubyのブロック というにパイプを繋げたいと思ってpry-command_resultっていうのを作った。

Pryのコマンドっていうのは

pry> $ Pry.run_command

From: /Users/toqoz/.rbenv/versions/1.9.3-p327-perf/lib/ruby/gems/1.9.1/gems/pry-0.9.11.3/lib/pry/pry_class.rb @ line 232:
Owner: #<Class:Pry>
Visibility: public
Number of lines: 14

def self.run_command(command_string, options={})
  options = {    :context => TOPLEVEL_BINDING,
    :show_output => true,
    :output => Pry.output,
    :commands => Pry.commands
  }.merge!(options)

  output = options[:show_output] ? options[:output] : StringIO.new

  Pry.new(:output => output, :input => StringIO.new("#{command_string}\nexit-all\n"),
          :commands => options[:commands],
          :prompt => proc {""}, :hooks => Pry::Hooks.new).repl(options[:context])
end
=> nil

みたいな感じでnilが返されて再利用性がない。そこでそんな再利用するようなコマンドがないという話があるかも知れないが、それは再利用できない状況であるからそのようなコマンドしか生まれなかったみたいな感じなのではないかと個人的に思っている。pry-command_resultを使うとこんな感じになる。

pry> command_result('$ Pry.run_command')
=> "\nFrom: /Users/toqoz/.rbenv/versions/1.9.3-p327-perf/lib/ruby/gems/1.9.1/gems/pry-0.9.11.3/lib/pry/pry_class.rb @ line 232:\nOwner: #<Class:Pry>\nVisibility: public\nNumber of lines: 14\n\ndef self.run_command(command_string, options={})\n  options = {\n    :context => TOPLEVEL_BINDING,\n    :show_output => true,\n    :output => Pry.output,\n    :commands => Pry.commands\n  }.merge!(options)\n\n  output = options[:show_output] ? options[:output] : StringIO.new\n\n  Pry.new(:output => output, :input => StringIO.new(\"\#{command_string}\\nexit-all\\n\"),\n          :commands => options[:commands],\n          :prompt => proc {\"\"}, :hooks => Pry::Hooks.new).repl(options[:context])\nend\n"

整形して見たければ

pry> puts _
From: /Users/toqoz/.rbenv/versions/1.9.3-p327-perf/lib/ruby/gems/1.9.1/gems/pry-0.9.11.3/lib/pry/pry_class.rb @ line 232:
Owner: #<Class:Pry>
Visibility: public
Number of lines: 14

def self.run_command(command_string, options={})
  options = {    :context => TOPLEVEL_BINDING,
    :show_output => true,
    :output => Pry.output,
    :commands => Pry.commands
  }.merge!(options)

  output = options[:show_output] ? options[:output] : StringIO.new

  Pry.new(:output => output, :input => StringIO.new("#{command_string}\nexit-all\n"),
          :commands => options[:commands],
          :prompt => proc {""}, :hooks => Pry::Hooks.new).repl(options[:context])
end
=> nil

とすれば良い。

例えば Pry.run_commandがどこに書いてあるかだけ知りたいとき、pry-pipelineと組み合わせると、こう書ける。

pry> command_result('$ Pry.run_command') | -> v { v.lines.grep(/From/).join("\n") }
=> "From: /Users/toqoz/.rbenv/versions/1.9.3-p327-perf/lib/ruby/gems/1.9.1/gems/pry-0.9.11.3/lib/pry/pry_class.rb @ line 232:\n"

詳しくは - https://github.com/ToQoz/pry-command_result - https://github.com/ToQoz/pry-pipeline