Skip to content

Instantly share code, notes, and snippets.

@cciollaro
Last active December 18, 2015 11:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cciollaro/5776864 to your computer and use it in GitHub Desktop.
Save cciollaro/5776864 to your computer and use it in GitHub Desktop.
Tree Builder DSL
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