lundi 24 octobre 2016

Ruby ERB template separate files

I have the following two files: shoplist.html.erb, shoplist.rb.

I want these two files to create an html file called list.html Here is the code to the first and second file.

shoplist.html.erb

      <!DOCTYPE html>
<html>
<head>
<% # %A - weekday, %d - day of the month, %B - full month name, %Y - year %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Shopping List for <%= @date.strftime('%A, %d %B %Y') %></title>
</head>
<body>
  <h1>Shopping List for <%= @date.strftime('%A, %d %B %Y') %></h1>
            <p>You need to buy:</p>
            <ul>
              <% for @item in @items %>
                <li><%= h(@item) %></li>
              <% end %>
            </ul>
  </body>
  </html>

shoplist.rb

require 'erb'

def get_items()
  ['bread', 'milk', 'eggs', 'spam']
end
def get_template(file)
  str = ""
  File.open(file,"r") do |f|
    f.each_line do |line|
      str << line
    end
  end                                                                                                                                 
  str
end

class ShoppingList
  include ERB::Util
  attr_accessor :items, :template, :date

  def initialize(items, template, date=Time.now)
    @date = date
    @items = items
    @template = template
  end

  def render()
    ERB.new(@template).result(binding)
  end

  def save(file)
    File.open(file, "w+") do |f|
      f.write(render)
    end
  end

end
list = ShoppingList.new(get_items, get_template(ARGV[0]))
list.save(File.join(ENV['PWD'], 'list.html'))

I know these files should theoretically work, but I don't know the proper way to run them through the terminal. These files were found online at the following link: link

When I look at the code, I notice that it takes in an argument for the filename. My theory was to pass the shoplist.html.erb file in as the argument through the terminal to get it to properly create the file. This was the terminal command I tried:

ruby shoplist.rb shoplist.html.erb

When I did that however it gave me the following error:

shoplist.rb:38:in `<main>': undefined local variable or method `list' for main:Object (NameError)

Can someone tell me what I'm doing wrong? Both of those files are in the same directory. I thought I could simply pass in the filename and have the get_template() function read the contents to create the html file. This doesn't appear to be the case. Thanks!

Aucun commentaire:

Enregistrer un commentaire