Skip to content

Instantly share code, notes, and snippets.

@briancicutti
Created April 4, 2013 14:50
Show Gist options
  • Save briancicutti/5311013 to your computer and use it in GitHub Desktop.
Save briancicutti/5311013 to your computer and use it in GitHub Desktop.
Fun metaprogramming, blocks, and some tricks with Ruby (basically a quick replication of what builder gem does)
class Builder
def initialize
@tag_stack = []
end
def method_missing(name, *args, &blk)
print " "*@tag_stack.size
print "<#{name}" + attributes(args) + ">"
@tag_stack.push name
if block_given?
puts
instance_eval &blk
else
self
end
@tag_stack.pop
print " "*@tag_stack.size
puts "</#{name}>"
end
def attributes args
if args.nil? || args[0].nil?
""
else
h = args[0]
" " + (h.keys.map{ |k| %Q[#{k}="#{h[k]}"] }).join(" ")
end
end
end
Builder.new.html do
head
body { div({"id" => "family", "class" => "child"}){div} }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment