Is there a way to make this look a little better?
conn.exec \'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \' +
\'from table1, table2, ta
Yes, if you don't mind the extra newlines being inserted:
conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc'
Alternatively you can use a heredoc:
conn.exec <<-eos
select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos
Sometimes is worth to remove new line characters \n
like:
conn.exec <<-eos.squish
select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos
If you do mind extra spaces and newlines, you can use
conn.exec %w{select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc} * ' '
(use %W for interpolated strings)
Like you, I was also looking for a solution which does not include newlines. (While they may be safe in SQL, they're not safe in my case and I have a large block of text to deal with)
This is arguably just as ugly, but you can backslash-escape newlines in a heredoc to omit them from the resulting string:
conn.exec <<~END_OF_INPUT
select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \
from table1, table2, table3, etc, etc, etc, etc, etc, \
where etc etc etc etc etc etc etc etc etc etc etc etc etc
END_OF_INPUT
Note that you cannot due this without interpolation (I.E. <<~'END_OF_INPUT'
) so be careful. #{expressions}
will be evaluated here, whereas they will not in your original code. A. Wilson's answer may be better for that reason.
In ruby 2.0 you can now just use %
For example:
SQL = %{
SELECT user, name
FROM users
WHERE users.id = #{var}
LIMIT #{var2}
}
Other options:
#multi line string
multiline_string = <<EOM
This is a very long string
that contains interpolation
like #{4 + 5} \n\n
EOM
puts multiline_string
#another option for multiline string
message = <<-EOF
asdfasdfsador #{2+2} this month.
asdfadsfasdfadsfad.
EOF
puts message