| 1 |
require "erb" |
| 2 |
|
| 3 |
# Build template data class. |
| 4 |
class Product |
| 5 |
def initialize( code, name, desc, cost ) |
| 6 |
@code = code |
| 7 |
@name = name |
| 8 |
@desc = desc |
| 9 |
@cost = cost |
| 10 |
|
| 11 |
@features = [ ] |
| 12 |
end |
| 13 |
|
| 14 |
def add_feature( feature ) |
| 15 |
@features << feature |
| 16 |
end |
| 17 |
|
| 18 |
# Support templating of member data. |
| 19 |
def get_binding |
| 20 |
binding |
| 21 |
end |
| 22 |
|
| 23 |
# ... |
| 24 |
end |
| 25 |
|
| 26 |
# Create template. |
| 27 |
template = %{ |
| 28 |
<html> |
| 29 |
<head><title>Ruby Toys -- <%= @name %></title></head> |
| 30 |
<body> |
| 31 |
|
| 32 |
<h1><%= @name %> (<%= @code %>)</h1> |
| 33 |
<p><%= @desc %></p> |
| 34 |
|
| 35 |
<ul> |
| 36 |
<% @features.each do |f| %> |
| 37 |
<li><b><%= f %></b></li> |
| 38 |
<% end %> |
| 39 |
</ul> |
| 40 |
|
| 41 |
<p> |
| 42 |
<% if @cost < 10 %> |
| 43 |
<b>Only <%= @cost %>!!!</b> |
| 44 |
<% else %> |
| 45 |
Call for a price, today! |
| 46 |
<% end %> |
| 47 |
</p> |
| 48 |
|
| 49 |
</body> |
| 50 |
</html> |
| 51 |
}.gsub(/^ /, '') |
| 52 |
|
| 53 |
rhtml = ERB.new(template) |
| 54 |
|
| 55 |
# Set up template data. |
| 56 |
toy = Product.new( "TZ-1002", |
| 57 |
"Rubysapien", |
| 58 |
"Geek's Best Friend! Responds to Ruby commands...", |
| 59 |
999.95 ) |
| 60 |
toy.add_feature("Listens for verbal commands in the Ruby language!") |
| 61 |
toy.add_feature("Ignores Perl, Java, and all C variants.") |
| 62 |
toy.add_feature("Karate-Chop Action!!!") |
| 63 |
toy.add_feature("Matz signature on left leg.") |
| 64 |
toy.add_feature("Gem studded eyes... Rubies, of course!") |
| 65 |
|
| 66 |
# Produce result. |
| 67 |
rhtml.run(toy.get_binding) |
| 68 |
|
| 69 |
# From https://docs.ruby-lang.org/en/2.3.0/ERB.html#class-ERB-label-Examples |