开发者

Can someone explain this ruby code?

开发者 https://www.devze.com 2023-03-11 17:03 出处:网络
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.

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 goin开发者_如何学Cg on here?


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")
0

精彩评论

暂无评论...
验证码 换一张
取 消