简体   繁体   English

以<< - HTML开头的ruby块

[英]ruby block that starts with <<-HTML

I'm learning about integrating Devise flash and error messages with Bootstrap (or in my case Materialize). 我正在学习如何将Devise flash和错误消息与Bootstrap(或者在我的案例中为Materialise)集成。 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. 我在Devise的wiki中找到了一篇关于这个主题的文章( https://github.com/plataformatec/devise/wiki/How-To:-Integrate-I18n-Flash-Messages-with-Devise-and-Bootstrap ),所以我理解如何工作,但有一部分代码我有理解的问题。

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

html.html_safe

Can someone explain the <<-HTML syntax? 有人可以解释<<-HTML语法吗? 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): 声明字符串的常用方法,在某些情况下非常有用(编辑: http//en.wikipedia.org/wiki/Here_document,感谢@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! 想象一下,在没有任何换行符的情况下阅读非常复杂的SQL查询会很痛苦! (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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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