LoginSignup
18
15

More than 5 years have passed since last update.

Rubyのヒアドキュメントでインデントを綺麗にするいくつか

Last updated at Posted at 2017-02-09

<<~ or String#strip_heredoc

Ruby2.3以降であれば<<~とを使うといい。

def foo
  puts <<~STR
    foo
      bar
        baz
  STR
end

もしくはActiveSupportのString#strip_heredocでも同様のことができるが、素直にRuby2.3以降にバージョンアップして<<~のが良い。

if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.

    Supported options are:
      -h         This message
      ...
  USAGE
end

String#squish

長い1行の記述を書くときにはString#squishが便利。ヒアドキュメント中は80行や120行などで改行いれて書くけど結果は1行になる。

def lock!(lock = true)
  if persisted?
    if changed?
      ActiveSupport::Deprecation.warn(<<-MSG.squish)
        Locking a record with unpersisted changes is deprecated and will raise an
        exception in Rails 5.2. Use `save` to persist the changes, or `reload` to
        discard them explicitly.
      MSG
    end
    reload(lock: lock)
  end
  self
end

ヒアドキュメントの戻り値は以下のとおり1行になる(冒頭と末尾のホワイトスペース、連続したホワイトスペースは1つのスペースに変換される)

=> "Locking a record with unpersisted changes is deprecated and will raise an exception in Rails 5.2. Use `save` to persist the changes, or `reload` to discard them explicitly."
18
15
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
18
15