Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 293
Marklar Avatar asked Jan 02 '13 18:01

Marklar


2 Answers

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.

like image 158
steel Avatar answered Nov 02 '22 16:11

steel


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;"
like image 41
Niklas B. Avatar answered Nov 02 '22 17:11

Niklas B.