erb snippets

How to display Flash messages in Rails

Tagged flash, rails, erb, haml  Languages ruby

Place the following in your ERB view:

<% [:info, :error].each do |key| %>
  <% if flash[key] %>
  <div class="<%= key %>" id="flash">
    <%= flash[key] %>
  </div>
  <% end %>
<% end %>

or use the following if you prefer Haml:

- [:notice, :error, :success].each do |key|
  - unless flash[key].blank?
    %p{ :class => "flash #{key}" }= flash[key]

Rendering ERB standalone

Tagged erb, ruby  Languages ruby

How to Render ERB standalone

#
# Renders an ERB template.
#
# Example:
#
#  assert_equal "world", Utils::ERB.render(
#    template: "<%= hello %>",
#    locals: { hello: "world"}
#  )
#
def self.render(template:, locals:)
  locals = Struct.new(*locals.keys).new(*locals.values) if locals.is_a?(Hash)
  # dash => trim whitespaces, e.g., <% if x = y -%>
  ::ERB.new(template, nil, '-').result(locals.instance_eval { binding })
rescue Exception => e
  message = "#{e.class}: #{e} "
  line = e.backtrace.grep(/^\(erb\)/)[0]
  if line
    line_no = line.split(':')[1].to_i
    message += "while evaluating line #{line_no}:\n"
    message += template.split("\n")[line_no-1]
    message += "\nBacktrace: " + e.backtrace.join("\n")
    raise e.class, message
  end
  raise e
end