[英]How do I use the Ruby attributes template, shop_items, and date to do the required tasks?
require 'erb'
class ShoppingList
attr_reader :template
attr_reader :shopping_items
attr_reader :date
def initialize(shopping_items, template, date = Time.now)
@template = template
@shopping_items = shopping_items
@date = date
end
def output(output_file)
File.write(output_file, render)
end
private
def render
ERB.new(@template).result(binding)
end
end
def shopping_items
["milk", "egg", "ham", "bread"]
end
def template
%{
<html>
<head></head>
<body>
<h1> Shopping List for <%= @date.strftime('%A, %d, %B, %Y')%></h1>
<p> You need to buy </p>
<ul>
<% @shopping_items.each do |item| %>
<li><%= item %></li>
<% end %>
</ul>
</doby>
</html>
}
end
ShoppingList.new(shopping_items, template).output('shopping_list.html')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.