Marklar
Marklar

Reputation: 1056

Whitespace with multiline string in ruby

I have a whitespace issue with multiline strings.

I have something similar to this in my code where I'm generating some SQL.

def generate_sql
   <<-EOQ
      UPDATE page
         SET view_count = 10;
   EOQ
end

But then my SQL indention is all messed up, which I don't really want.

"       UPDATE page\n          SET view_count = 10;\n"

I could do

    def generate_sql
<<-EOQ
UPDATE page
   SET view_count = 10;
EOQ
    end

Which outputs exactly what I want

"UPDATE page\n   SET view_count = 10;\n" 

But then my code indention is all messed up, which I don't really want.

Any suggestions on how best to achieve what I'm after?

Upvotes: 9

Views: 3047

Answers (4)

steel
steel

Reputation: 12580

Ruby 2.3.0 solves this nicely with the squiggly heredoc. Note the difference of the tilde/hyphen between examples.

hyphen_heredoc = <<-MULTILINE_STRING
                    One line
                    Second line
                      Indented two spaces
                    MULTILINE_STRING

squiggly_heredoc = <<~MULTILINE_STRING_WITH_TILDE
                      One line
                      Second line
                        Indented two spaces
                      MULTILINE_STRING_WITH_TILDE

2.3.0 :001 > puts hyphen_heredoc
                      One line
                      Second line
                        Indented two spaces
2.3.0 :002 > puts squiggly_heredoc
One line
Second line
  Indented two spaces

With the squiggly heredoc, The indentation of the least-indented line will be removed from each line of the content.

Upvotes: 9

This takes a little more space (and is perhaps less pretty) but works well:

def generate_sql
   text = <<-EOQ
      UPDATE page
         SET view_count = 10;
   EOQ
   text.gsub(/^#{text.match(/^\s*/)[0]}/, '')
end

gives

"UPDATE page\n   SET view_count = 10;\n"

Upvotes: 2

Dave S.
Dave S.

Reputation: 6429

Something like this ought to do it:

def generate_sql
  <<-EOQ.gsub("\n", " ").strip
    UPDATE page
      SET ...
  EOQ
end

Though in this case, your DB will ignore the whitespace, so it may not be worth going to the trouble.

Upvotes: 2

Niklas B.
Niklas B.

Reputation: 95368

There are libraries like ruby-dedent that let you do

require 'dedent'

def generate_sql
   <<-EOQ.dedent
      UPDATE page
         SET view_count = 10;
   EOQ
end

Which results in

"UPDATE page\n   SET view_count = 10;"

Upvotes: 7

Related Questions