简体   繁体   中英

ruby block that starts with <<-HTML

I'm learning about integrating Devise flash and error messages with Bootstrap (or in my case Materialize). I found an article on the topic within Devise's wiki ( https://github.com/plataformatec/devise/wiki/How-To:-Integrate-I18n-Flash-Messages-with-Devise-and-Bootstrap ), so I understand how it has to work, but there was a section of the code I'm having problems understanding.

html = <<-HTML
<div class="card-panel red lighten-2"> 
  #{messages}
</div>
HTML

html.html_safe

Can someone explain the <<-HTML syntax? BTW, here is the full function in case you need context

def devise_error_messages!
return '' if resource.errors.empty?

messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
html = <<-HTML
<div class="card-panel red lighten-2"> 
  #{messages}
</div>
HTML

html.html_safe
end

This is a ruby common way to declare a string, it is pretty useful in some cases (edit: http://en.wikipedia.org/wiki/Here_document thanks to @Stefan):

sql = <<-SQL
  SELECT * FROM users
  WHERE users.id > 15
  ORDER BY users.username;
SQL
ActiveRecord::Base.connection.execute(sql)

Way better to read this than a simple:

sql = "SELECT * FROM users WHERE users.id > 15 ORDER BY users.username;"
ActiveRecord::Base.connection.execute(sql)

Imagine the pain to read a very complex SQL query without any line-break! (like with a manual join, recursive, union or views of table(s)!


It works with any kind of word:

a_string = <<-WHATEVER
  This is a string
  with some line-break
  to make it more readable
  #{and_you_can_use_string_interpolation_too}
WHATEVER

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM