Home > Mobile >  How to use HEREDOC to pass as an argument to a method?
How to use HEREDOC to pass as an argument to a method?

Time:09-13

Code example:

create_data_with(
  first: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  second: <<~TEXT
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  TEXT,
  third: "Nunc aliquet ipsum at semper sodales."
)

The error is present in this line:

second: <<~TEXT

RuboCop describes it like this:

Lint/Syntax: unterminated string meets end of file
(Using Ruby 3.1 parser; configure using TargetRubyVersion parameter, under AllCops)
      second: <<~TEXT

Can you please tell me what should be the syntax? I need to keep the look and use of <<~.

CodePudding user response:

Another option is to move the heredoc after the method call. However, since the heredoc starts on the line following its identifier, your method call must not span multiple lines:

create_data_with(first: "foo", second: <<~TEXT, third: "bar")
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  TEXT

For longer values, you could use multiple heredocs:

create_data_with(first: <<~FIRST, second: <<~SECOND, third: <<~THIRD)
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  FIRST
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  SECOND
    Nunc aliquet ipsum at semper sodales.
  THIRD

CodePudding user response:

With heredocs, the parser expects the exact delimiter to close the literal. You open with TEXT, but you close with TEXT, and ruby doesn't consider this literal closed. However, you can (and should in this case) put the comma after the opening delimiter. Here's a fix:

create_data_with(
  first: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  second: <<~TEXT,
    Aenean vel ex bibendum, egestas tortor sit amet, tempus lorem. Ut sit
    amet rhoncus eros. Vestibulum ante ipsum primis in faucibus orci
    luctus et ultrices posuere cubilia curae; Quisque non risus vel lacus
    tristique laoreet. Curabitur quis auctor mauris, nec tempus mauris.
  TEXT
  third: "Nunc aliquet ipsum at semper sodales."
)

You can even call methods this way. For example, the squiggly heredoc (<<~TEXT) was previously done in rails as <<-TEXT.strip_heredoc

  • Related