Created
December 6, 2009 13:56
-
-
Save dchest/250234 to your computer and use it in GitHub Desktop.
Simple toy html writer in ruby
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
# Simple toy html writer in ruby | |
def tag(name, *args) | |
a = args.length > 0 ? " " + args.join(" ") : "" | |
a = "" if a == " " | |
name = "p" if name == "§" | |
block_given? ? "<#{name}#{a}>" + yield + "</#{name}>\n" : "<#{name}#{a} />" | |
end | |
def defmacro(name) | |
eval "def #{name}(*args)\n" + yield + "\nend" | |
end | |
TAGS = %w[body b strong i em br hr img head title h1 h2 h3 h4 h5 h6 § div input] | |
TAGS.each { |t| | |
defmacro(t) { "block_given? ? tag(\"#{t}\", args) { yield } : tag(\"#{t}\", args)" } | |
} | |
# html macro prints its block | |
defmacro(:html) { "print tag(:html) { yield }" } | |
# Example | |
html { | |
head { | |
title { "Welcome page" } | |
} + | |
body { | |
h1 { "Welcome!" } + | |
§ { "This is a test page of " + b { "HTML" } + " generated by Ruby." + br + | |
"Nice, isn't " + em { "it" } + "?" } + | |
input("type=submit", "name=ok", "value=OK") + | |
§ { "This is it" } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment