How do I remove leading whitespace chars from Ruby HEREDOC?

后端 未结 11 712
误落风尘
误落风尘 2020-11-28 22:09

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 supp

11条回答
  •  旧时难觅i
    2020-11-28 22:52

    Not much to do that I know of I'm afraid. I usually do:

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

    That works but is a bit of a hack.

    EDIT: Taking inspiration from Rene Saarsoo below, I'd suggest something like this instead:

    class String
      def unindent 
        gsub(/^#{scan(/^\s*/).min_by{|l|l.length}}/, "")
      end
    end
    
    def distinct_count
        <<-EOF.unindent
            \tSELECT
            \t CAST('#{name}' AS VARCHAR(30)) as COLUMN_NAME
            \t,COUNT(DISTINCT #{name}) AS DISTINCT_COUNT
            \tFROM #{table.call}
        EOF
    end
    

    This version should handle when the first line is not the one farthest to the left too.

提交回复
热议问题