LoginSignup
52
49

More than 5 years have passed since last update.

Rubyのヒアドキュメントを美しく書くにはunindent gemが便利

Last updated at Posted at 2014-01-02

Rubyでヒアドキュメント書くとインデント崩れて汚い

class Foo
  def bar
    puts <<-EOS
hogehoge
blah blah ...
    EOS
  end
end

EOSの手前の-のおかげでEOSはインデントできますが、内容にもインデントを加えるとそれが文字列に入ってしまいます。
なのでhogehogeやblah blahはインデントできません。

解決案

  • ヒアドキュメントを便利にする String#undent メソッド
    • 元ネタはhomebrewのここですね。先頭行のインデント量を数えて各行の文字を消してます。実装が綺麗です。
    • このブログでは空行でない行のうち最もインデントが少ないもののインデント量を数えて各行の文字を消すように改良しています。

これ自体はいいんですが、この書き方をするたびにStringの拡張のためのソースをどこかに配置しなきゃいけないのは大変です。

unindent gemを使う

# Gemfile
gem 'unindent'
require 'unindent'

class Foo
  def bar
    puts <<-EOS.unindent
      hogehoge
      blah blah ...
    EOS
  end
end

綺麗ですね。
このunindent空行以外でインデントが最も少ない行で消すインデント量を取るので、1行目を少し低くしてても使えます。

追記

ActiveSupportのstrip_heredocでも同様のことができるようです!

52
49
3

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
52
49