Home > Net >  Properly typing a multiline string in ruby with sorbet
Properly typing a multiline string in ruby with sorbet

Time:12-17

I'm adopting Sorbet into a project and I can't understand how should I type the following constant:

RETRIEVE_FILE_URL_QUERY = <<~QUERY.freeze
query($input: ID!) {
  node(id: $input) {
    ... on BulkOperation {
      url
      partialDataUrl
    }
  }
}
QUERY

The fastest way should be

RETRIEVE_FILE_URL_QUERY = T.let(<<~QUERY.freeze
query($input: ID!) {
  node(id: $input) {
    ... on BulkOperation {
      url
      partialDataUrl
    }
  }
}
QUERY, String)

this is also the quick fix I got from vscode

But this raise the error

escape sequence meets end of file (2001)

As expected, since the heredoc name can't be no more found.

So I tried

RETRIEVE_FILE_URL_QUERY = T.let(<<~QUERY.freeze
query($input: ID!) {
  node(id: $input) {
    ... on BulkOperation {
      url
      partialDataUrl
    }
  }
}
QUERY
, String)

But this raised another error:

T.untyped
unexpected token "," (2001)

With this, I got no clue how should I handle it.

I know that I could use the concatenation operator ( ) but I would like to not split this string.

I'm still new to ruby so I want to ask you if there is a way to handle this.

CodePudding user response:

Your "fastest" way violates the syntax. The terminating token must be on a line by itself.

When you do this:

QUERY, String)

You've put in something other than the terminator token QUERY, so it is assumed the string keeps going.

Remember that Ruby has multiple quoting systems, and is largely indifferent to multiple lines, as in:

RETRIEVE_FILE_URL_QUERY = "
query($input: ID!) {
  node(id: $input) {
    ... on BulkOperation {
      url
      partialDataUrl
    }
  }
}
".freeze

Where you could also use # frozen_string_literal: true to do the freezing for you automatically.

  • Related