Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

seeing_is_believing でサンプルコード実行結果のコメントをサクサクと生成する

seeing_is_believing とは?

Rubyの各行のコードの実行結果をコメントとして追記してくれるツールです。
ブログやGISTのサンプルコードでよくみるようなものです。

例えば

text = "hoge"
text*2
text.upcase
text.downcase

に対して、以下のようなコメントをつけるようなやつです。

text = "hoge"  # => "hoge"
text*2         # => "hogehoge"
text.upcase    # => "HOGE"
text.downcase  # => "hoge"

Atom Package

seeing_is_believing は様々な Editor の Plugin として提供されています。
私は Atom を利用しているので Atom 版をインストールします。

インストール

まず、 seeing_is_believing gem をインストールします

$ gem install seeing_is_believing

次に AtomGUI からパッケージをインストールします。

f:id:tbpg:20170406005250p:plain

デモ

その1

cmd + alt + b で全ての行を対象に実行します。

f:id:tbpg:20170406005259g:plain

  • 変換前のコード
text = "hoge"
text*2
text.upcase
text.downcase
  • 変換後のコード
text = "hoge"  # => "hoge"
text*2         # => "hogehoge"
text.upcase    # => "HOGE"
text.downcase  # => "hoge"

その2

cmd + alt + n で、マーカー( # => )をつけた場所だけ実行します

f:id:tbpg:20170406005309g:plain

  • 変換前のコード
def fizzbuzz(limit)
  (1..limit).each_with_object([]) do |e, memo|
    memo << case
    when e % 15 == 0 then "FizzBuzz"
    when e % 5 == 0 then "Buzz"
    when e % 3 == 0 then "Fizz"
    else e.to_s
    end
  end
end

fizzbuzz(3)
fizzbuzz(15)
  • 変換後のコード
def fizzbuzz(limit)
  (1..limit).each_with_object([]) do |e, memo|
    memo << case
    when e % 15 == 0 then "FizzBuzz"
    when e % 5 == 0 then "Buzz"
    when e % 3 == 0 then "Fizz"
    else e.to_s
    end
  end
end

fizzbuzz(3)  # => ["1", "2", "Fizz"]
fizzbuzz(15) # => ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]

補足

他エディタ

seeing_is_believing の Atom 以外のエディタ向け Plugin 情報は以下

JS版

js 向けがあるようです。

関連情報