Skip to content

Instantly share code, notes, and snippets.

@pootsbook
Created March 9, 2021 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pootsbook/ebe93033a1543c8ddf3ccde8ca5ea441 to your computer and use it in GitHub Desktop.
Save pootsbook/ebe93033a1543c8ddf3ccde8ca5ea441 to your computer and use it in GitHub Desktop.
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