|
| 1 | +# Define Multiline Strings With Heredocs |
| 2 | + |
| 3 | +[A _heredoc_ (_here document_) is a special ruby |
| 4 | +syntax](https://ruby-doc.org/core-2.5.0/doc/syntax/literals_rdoc.html#label-Here+Documents) |
| 5 | +for defining formatted multiline strings. These are useful for any situation |
| 6 | +where you need to define a block of text where newlines and indentation are |
| 7 | +preserved -- e.g. output an error, help message, or some formatted SQL. |
| 8 | + |
| 9 | +The standard syntax is defined with `<<` and some uppercase identifier (e.g. |
| 10 | +`TXT`, `DOC`, `SQL`, etc.) to open and close the multiline string. |
| 11 | + |
| 12 | +```ruby |
| 13 | +def lookup_team(team_id) |
| 14 | + query = <<SQL |
| 15 | + select users.id from users |
| 16 | + join teams |
| 17 | + on teams.id = users.team_id |
| 18 | + where teams.id = #{team_id} |
| 19 | + order by created_at desc |
| 20 | + limit 10; |
| 21 | +SQL |
| 22 | + |
| 23 | + team_member_ids = db.execute(query) |
| 24 | +end |
| 25 | +``` |
| 26 | + |
| 27 | +With the SQL formatted this way, it is easier to read and we can print/log out |
| 28 | +this nicely formatted version to make debugging easier. |
| 29 | + |
| 30 | +Notice that the terminating `SQL` identifier is fully left justified. I find |
| 31 | +that visually off relative to the indentation of everything else, so I like to |
| 32 | +use the _indented_ heredoc syntax (`<<-`). |
| 33 | + |
| 34 | +```ruby |
| 35 | +def lookup_team(team_id) |
| 36 | + query = <<-SQL |
| 37 | + select users.id from users |
| 38 | + join teams |
| 39 | + on teams.id = users.team_id |
| 40 | + where teams.id = #{team_id} |
| 41 | + order by created_at desc |
| 42 | + limit 10; |
| 43 | + SQL |
| 44 | + |
| 45 | + team_member_ids = db.execute(query) |
| 46 | +end |
| 47 | +``` |
0 commit comments