Skip to content

Instantly share code, notes, and snippets.

@bogdan
Created June 8, 2017 14:20
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 bogdan/9f3cc78e1625f60e50ed6fefc6c59a79 to your computer and use it in GitHub Desktop.
Save bogdan/9f3cc78e1625f60e50ed6fefc6c59a79 to your computer and use it in GitHub Desktop.
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