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
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.
A block is the same thing as a method, but it does not belong to an object. Blocks are called closures in other programming languages. There are some important points about Blocks in Ruby: Block can accept arguments and returns a value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With