Created
April 4, 2013 14:50
-
-
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)
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 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