Last active
December 18, 2015 11:39
-
-
Save cciollaro/5776864 to your computer and use it in GitHub Desktop.
Tree Builder DSL
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 Tree | |
attr_accessor :elements | |
def initialize(&block) | |
@elements = '' | |
instance_eval(&block) | |
end | |
def method_missing(method_name, *args, &block) | |
@elements << "<#{method_name}>" | |
yield if block | |
@elements << "</#{method_name}>" | |
end | |
def inspect | |
puts @elements | |
end | |
end | |
Tree.new do | |
table do | |
tr do | |
td | |
td | |
end | |
end | |
end.inspect | |
#<table><tr><td></td><td></td></tr></table> | |
class HtmlBuilder | |
attr_accessor :result | |
def initialize(&block) | |
@result = '<html>' | |
instance_eval(&block) | |
@result << '</html>' | |
end | |
def method_missing(method_name, *args, &block) | |
@result << "<#{method_name}" | |
@result << parse_args(args.last) if args.last.is_a?(Hash) | |
@result << ">" | |
yield if block | |
@result << "</#{method_name}>" | |
end | |
def text(str) | |
@result << str | |
end | |
def parse_args(args) | |
ret = ' ' | |
args.each_pair {|key, value| ret << "#{key}=\"#{value}\""} | |
ret | |
end | |
def inspect | |
puts @result | |
end | |
end | |
HtmlBuilder.new do | |
title do | |
text "whatup" | |
end | |
body :onload => "alert('hi')" do | |
div :id => "hi", :class => "bye" do | |
text "hi_again" | |
end | |
end | |
end.inspect | |
#<html><title>whatup</title><body onload="alert('hi')"><div id="hi"class="bye">hi_again</div></body></html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment