LoginSignup
1
2

More than 5 years have passed since last update.

Pryにdeleteコマンドを定義して要らないbinding.pryを消しながら快適デバッグしたい

Posted at

binding.pryのあるある

prypry-byebugを使ってbinding.pryでデバッグするというのはめちゃくちゃ便利でRubyの開発には欠かせないものですが、
「もうここは止まらなくていいのに止まった。。。。要らないところ一つずつ消すの面倒くさい(泣)」
という経験があるのはぼくだけでは無いかと思います。

要らないところは消しながら進めれば良いのですが、残念ながらそういうコマンドは用意されていません。

そこで今回は独自にdeleteというコマンドを定義して削除する方法を考えました。

.pryrcに以下を追記します。
コードがかなり複雑なんですが

class Pry
  @delete_history = {}
  class << self
    attr_accessor :delete_history
  end
end

default_command_set = Pry::CommandSet.new do
  command "delete", "delete current binding.pry from file" do
    file_name, current_line =
    Pry::Command::Edit::FileAndLineLocator.from_binding(_pry_.current_binding)
    Pry.delete_history[file_name] ||= 0

    lines = IO.readlines(file_name).map.with_index(1) do |line, index|
      if line.match?(/binding.pry(\s)?/) && index <= (current_line - (1 + Pry.delete_history[file_name]))
        print("#{file_name}:#{index} deleted\n")
        Pry.delete_history[file_name] += 1
        line.gsub!(/binding.pry(\s)?/, "")
        line.match?(/\A[[:space:]]*\z/) ? nil : line
      else
        line
      end
    end

    File.open(file_name, 'w') do |file|
      file.puts lines.compact
    end
  end
end

Pry.config.commands.import default_command_set

これである程度は削除できます。

    44:   binding.pry
 => 45:   RECORD_KEYS = [
    46:     "user",
    47:     "user_name",
    48:     "text",
    49:     "ts",
    50:     "datetime"

[1] pry(TimeSheetWriter)> delete
"44:   binding.pry\n delete!!"

なぜある程度かというと一度削除するとそのファイルが全体として1行ずれてしまうためです。
で単純に上から削除していく場合はいいのですが、順番を前後して削除しているパターンなどは対応しきれていません。
惜しいところまで来ているので後もう一歩のところです。
もう少しいい感じにできたら更に更新したものをアップしようと思います。

1
2
0

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
1
2