Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain this ruby code?

From the rails postgresql_adapter.rb. I get what it's trying to do, I just don't get how it happens. It's really to do with the <<-SQL that I'm lost.

exec_query(<<-SQL, 'SCHEMA', binds).rows.first[0].to_i > 0
  SELECT COUNT(*)
  FROM pg_tables
  WHERE tablename = $1
  #{schema ? "AND schemaname = $2" : ''}
SQL

I've seen code before where you could say:

blah = <<-X
 some
 lines
 of
 test
X

But I've never seen this done within the argument to a function call. I'm really confused by this. Can someone explain to me what exactly is going on here?

like image 865
brad Avatar asked Dec 13 '22 12:12

brad


1 Answers

You can use a heredoc-marker (like <<-SQL in your example) anywhere (or even multiple times) in a line and the heredoc will then start on the following line and continue until the end-marker is met (in case of multiple markers, the (n+1)th heredoc will start after the nth end-marker and continue up to the (n+1)th end-marker). The content of each heredoc will then be inserted at the place where the corresponding marker was used.

So

foo(<<BAR, 42)
bar
BAR

is the same as

foo("bar\n", 42)

and

foo(<<BAR, <<BAZ)
bar
BAR
baz
BAZ

is the same as

foo("bar\n", "baz\n")
like image 127
sepp2k Avatar answered Jan 04 '23 02:01

sepp2k