Skip to content

Instantly share code, notes, and snippets.

@pootsbook
Last active Mar 17, 2021
Embed
What would you like to do?
class HTMLDocument
VOID_ELEMENTS = %i[
area base br col embed hr img input
link meta param source track wbr
]
def initialize
@doc = ""
yield self if block_given?
end
def text(string)
@doc << string
end
def el(type, attrs={})
@doc << opening_tag(type, attrs)
unless VOID_ELEMENTS.include? type
yield
@doc << closing_tag(type)
end
end
def to_s
@doc
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
end
doc = HTMLDocument.new do |d|
d.el :html, lang: "en-GB" do
d.el :head do
d.el :title do
d.text "Hello, "
d.text "World!"
end
end
d.el :body do
d.el :input, { type: "text" }
end
end
end
puts doc.to_s
#=> <html lang="en-GB"><head><title>Hello, World!</title></head><body><input type="text"></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment