Last active
March 17, 2021 07:07
-
-
Save pootsbook/c3869f089af6fb1cf1fd53bc0250961b to your computer and use it in GitHub Desktop.
Final-ish Implementation of an HTML helper, see: https://www.crossingtheruby.com/2021/03/10/a-small-html-helper-library-5.html
This file contains 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 | |
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