Created
June 8, 2017 14:20
-
-
Save bogdan/9f3cc78e1625f60e50ed6fefc6c59a79 to your computer and use it in GitHub Desktop.
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 Generator | |
class Tag | |
attr_accessort :name, :children, :level | |
def initialize(name, level = 0, &block) | |
@name = name | |
@level = level | |
@children = [] | |
instance_eval(&block) | |
end | |
def to_html | |
[ | |
shift + "<#{name}>", | |
children.map(&:to_html), | |
shift + "</#{name}>", | |
].join("\n") | |
end | |
def shift | |
" " * level | |
end | |
def tag(name, &block) | |
@children << Tag.new(name, level + 1, &block) | |
end | |
def text(string) | |
@children << Text.new(string, level + 1) | |
end | |
def change(*names, &block) | |
if names.empty? | |
@children = [] | |
instance_eval(&block) | |
return true | |
else | |
return @children.any? do |child| | |
if child.is_a?(Tag) | |
child.change(names[1..-1], &block) | |
end | |
end | |
end | |
end | |
end | |
class Text | |
attr_accessort :string | |
def to_html | |
string | |
end | |
end | |
def html(&block) | |
Tag.new('html', &block).to_html | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment