0

The following is code from an ERB tutorial. When I tried to execute the code, the compiler complained saying "(erb):16: undefined local variable or method `priority' for main:Object (NameError)". I cannot figure out the reason. Could someone please help me out?

require "erb"

# Create template.
template = %q{
  From:  James Edward Gray II <james@grayproductions.net>
  To:  <%= to %>
  Subject:  Addressing Needs

  <%= to[/\w+/] %>:

  Just wanted to send a quick note assuring that your needs are being
  addressed.

  I want you to know that my team will keep working on the issues,
  especially:

  <%# ignore numerous minor requests -- focus on priorities %>
  % priorities.each do |priority|
    * <%= priority %>
  % end

  Thanks for your patience.

  James Edward Gray II
}.gsub(/^  /, '')

message = ERB.new(template, 0, "%<>")

# Set up template data.
to = "Community Spokesman <spokesman@ruby_community.org>"
priorities = [ "Run Ruby Quiz",
               "Document Modules",
               "Answer Questions on Ruby Talk" ]

# Produce result.
email = message.result
puts email
Terry Li
  • 16,870
  • 30
  • 89
  • 134

1 Answers1

0

That ERB template looks mangled, a problem caused by your indentation. You just need to fix the middle:

  <% priorities.each do |priority| %>
    * <%= priority %>
  <% end %>

The alternate syntax is to have a % at the very beginning of the line. In your case you have inadvertently added some spaces which are rendering that part of the ERB invalid.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • by the way what does gsub do in this case? to replace within the template or the generated text? – Terry Li Jun 02 '11 at 17:10
  • It removes the first two spaces at the beginning of each line in the string. This seems to fix the indentation problem, but is really a sub-optimial solution. It's better to use a `<<`-style HERE doc. – tadman Jun 02 '11 at 20:00