Created
March 9, 2021 00:28
-
-
Save pootsbook/ebe93033a1543c8ddf3ccde8ca5ea441 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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