Skip to content

Instantly share code, notes, and snippets.

@alloy
Created February 4, 2009 11:21
Show Gist options
  • Save alloy/58060 to your computer and use it in GitHub Desktop.
Save alloy/58060 to your computer and use it in GitHub Desktop.
require "pp"
class Builder
def initialize
@elements = []
end
%w{ html body h1 ul li }.each do |tag|
eval %{
def #{tag}(*args)
if block_given?
nested_builder = Builder.new
yield nested_builder
@elements << [:#{tag}, nested_builder]
else
@elements << [:#{tag}, args]
end
end
}
def to_s
@elements.map { |tag, value| "<#{tag}>#{value.to_s}</#{tag}>" }.join
end
end
end
mab = Builder.new
mab.html do |h|
h.body do |b|
b.h1 "Boats.com has great deals"
b.ul do |ul|
ul.li "$49 for a canoe"
ul.li "$39 for a raft"
ul.li "$29 for a huge boot that floats and can fit 5 people"
end
end
end
pp mab
# #<Builder:0x1b6de0
# @elements=
# [[:html,
# #<Builder:0x1b57c4
# @elements=
# [[:body,
# #<Builder:0x1b574c
# @elements=
# [[:h1, ["Boats.com has great deals"]],
# [:ul,
# #<Builder:0x1b5698
# @elements=
# [[:li, ["$49 for a canoe"]],
# [:li, ["$39 for a raft"]],
# [:li,
# ["$29 for a huge boot that floats and can fit 5 people"]]]>]]>]]>]]>
p mab.to_s
# "<html><body><h1>Boats.com has great deals</h1><ul><li>$49 for a canoe</li><li>$39 for a raft</li><li>$29 for a huge boot that floats and can fit 5 people</li></ul></body></html>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment