Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 416
mike0416 Avatar asked Apr 08 '15 14:04

mike0416


People also ask

What does =~ mean in Ruby?

=~ 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.

What does %I mean in Ruby?

The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.

What is block given in Ruby?

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.


1 Answers

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
like image 189
MrYoshiji Avatar answered Sep 28 '22 09:09

MrYoshiji