Posted about 7 years ago. Visible to the public.

Using heredoc for prettier Ruby code

You can use heredoc to avoid endlessly long lines of code that nobody can read. It looks like this:

Copy
def long_message puts(<<-EOT) Here goes a very long message... Sincerely, Dr. Foobear EOT end

<<-EOT will be somewhat of a placeholder: anything you write in the line after you used it will be its value until you write EOT in a single line.

You can use any string to flag your heredocs. T0 be more verbose you can use something else – your IDE may even be aware of it, for example RubyMine understands <<-SQL, <<-HTML, <<-XML, <<-JSON, etc and highlights correctly.

Multiple heredocs in one line

Now what if you want to do this more than once per line? Easy:

Copy
def long_messages html_escape(<<-ONE) + '<hr />' + html_escape(<<-TWO) Here goes my first very long message. Yeehaw! ONE This is the second message which is still long. It is long indeed. TWO end

<<- vs <<

You can also omit the dash and just write <<EOT – if you do this, your terminating sequence must be at the very beginning of the line. It's less pretty:

Copy
def foo stuff do something(<<-EOT) + something_else Here goes my content. EOT # vs: something(<<EOT) + something_else Here goes my content. EOT end end

Notes & Caveats

  • Important: I somewhat cheated here. Any spaces from the beginning of a line will be part of the string:

    Copy
    puts <<-EOT Hello Universe EOT # Writes " Hello Universe\n"

    In many cases this is not a problem, e.g. when you want to pretty up many lines of monstrous SQL you would not care. Whenever you require one very specific string, like in specs, and if indentation causes you trouble, do not indent or just use a small method to strip leading spaces.

  • Using heredoc you will have a linebreak after the last line. This can cause trouble (again, like when used in specs) – you can hack around it by saying <<-EOT.sub(/\n$/, '').
  • You can use regular string interpolation inside heredoc:

    Copy
    puts <<EOT Dear #{user.name}, ... EOT

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
almost 4 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more