Created
June 27, 2020 17:43
-
-
Save condef5/197bd3f28ad247fdc6a7fae7c6875fba 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
# Temary | |
# ------------------------ | |
# Explain about how works: | |
# > class method self ✅ | |
# > method_missing ✅ | |
# > blocks as parameter ✅ | |
# > instance_eval ✅ | |
# What are we going to build? | |
# markup = Html.build do | |
# body do | |
# section class: "flex flex-col" do | |
# h1 "Dark is amazing", class: "title" | |
# p "Martha mata a jonas", class: "text-center", id: "martha" | |
# end | |
# end | |
# end | |
class Html | |
def initialize(&block) | |
@content = [] | |
@ident = 0 | |
instance_eval(&block) if block_given? | |
end | |
def method_missing(method, text = nil, **options, &block) | |
builder_tag(method, text, options, &block) | |
end | |
def get_html | |
@content.join("\n") | |
end | |
def self.build(&block) | |
builder = Html.new(&block) | |
builder.get_html | |
end | |
private | |
def builder_tag(tag, text, options, &block) | |
@content << "#{" " * @ident }<#{tag} #{builder_options(options)}>" | |
@ident += 2 | |
@content << "#{" " * @ident } " + text if text | |
instance_eval(&block) if block_given? | |
@ident -= 2 | |
@content << "#{" " * @ident }</#{tag}>" | |
end | |
def builder_options(options) | |
options.collect { |key, value| "#{key}='#{value}'"}.join(" ") | |
end | |
end | |
markup = Html.build do | |
section do | |
h1 "my title", class: "text-center", id: "my-id" # <h1> | |
h2 "my second title" | |
end | |
end | |
puts markup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Spoiler Warning