Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class HTMLDocument
def initialize
@doc = ""
yield self if block_given?
end
def el(type, attrs={})
case type
when :text
@doc << yield
when :input
@doc << opening_tag(type, attrs)
else
@doc << opening_tag(type, attrs)
yield
@doc << closing_tag(type)
end
end
def opening_tag(name, attrs)
if attrs.empty?
"<#{name}>"
else
"<#{name} #{attributes(attrs)}>"
end
end
def closing_tag(name)
"</#{name}>"
end
def attributes(attrs)
attrs.map do |key, value|
%Q(#{key}="#{value}")
end.join(" ")
end
def to_s
@doc
end
end
doc = HTMLDocument.new do |d|
d.el :html, lang: "en-GB" do
d.el :head do
d.el :title do
d.el :text do
"Hello, "
end
d.el :text do
"World!"
end
end
end
end
end
puts doc.to_s
#=> <html lang="en-GB"><head><title>Hello, World!</title></head></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment