Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove leading whitespace chars from Ruby HEREDOC?

I'm having a problem with a Ruby heredoc i'm trying to make. It's returning the leading whitespace from each line even though i'm including the - operator, which is supposed to suppress all leading whitespace characters. my method looks like this:

    def distinct_count     <<-EOF         \tSELECT         \t CAST('#{name}' AS VARCHAR(30)) as COLUMN_NAME         \t,COUNT(DISTINCT #{name}) AS DISTINCT_COUNT         \tFROM #{table.call}     EOF end 

and my output looks like this:

    => "            \tSELECT\n            \t CAST('SRC_ACCT_NUM' AS VARCHAR(30)) as COLUMN_NAME\n            \t,COUNT(DISTINCT SRC_ACCT_NUM) AS DISTINCT_COUNT\n         \tFROM UD461.MGMT_REPORT_HNB\n" 

this, of course, is right in this specific instance, except for all the spaces between the first " and \t. does anyone know what i'm doing wrong here?

like image 593
Chris Drappier Avatar asked Sep 22 '10 19:09

Chris Drappier


2 Answers

The <<- form of heredoc only ignores leading whitespace for the end delimiter.

With Ruby 2.3 and later you can use a squiggly heredoc (<<~) to suppress the leading whitespace of content lines:

def test   <<~END     First content line.       Two spaces here.     No space here.   END end  test # => "First content line.\n  Two spaces here.\nNo space here.\n" 

From the Ruby literals documentation:

The indentation of the least-indented line will be removed from each line of the content. Note that empty lines and lines consisting solely of literal tabs and spaces will be ignored for the purposes of determining indentation, but escaped tabs and spaces are considered non-indentation characters.

like image 133
Phil Ross Avatar answered Sep 23 '22 21:09

Phil Ross


If you're using Rails 3.0 or newer, try #strip_heredoc. This example from the docs prints the first three lines with no indentation, while retaining the last two lines' two-space indentation:

if options[:usage]   puts <<-USAGE.strip_heredoc     This command does such and such.       Supported options are:       -h         This message       ...   USAGE end 

The documentation also notes: "Technically, it looks for the least indented line in the whole string, and removes that amount of leading whitespace."

Here's the implementation from active_support/core_ext/string/strip.rb:

class String   def strip_heredoc     indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0     gsub(/^[ \t]{#{indent}}/, '')   end end 

And you can find the tests in test/core_ext/string_ext_test.rb.

like image 42
chrisk Avatar answered Sep 24 '22 21:09

chrisk