Created
June 29, 2009 20:37
-
-
Save tj/137785 to your computer and use it in GitHub Desktop.
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
module Tags | |
def tag name, contents = nil, attrs = {}, &block | |
contents, attrs = nil, contents if contents.is_a? Hash | |
create_tag name, contents, attrs, &block | |
end | |
def create_tag name, contents, attrs, &block | |
"<#{name} #{attrs.map { |k,v| %(#{k}="#{v}") }.join(' ') }>#{contents}</#{name}>\n" | |
end | |
end | |
module Buffer | |
class Base | |
def initialize | |
@buffer = '' | |
end | |
def create_tag *args, &block | |
@buffer << Buffer.create_tag(*args, &block) | |
end | |
def to_s | |
@buffer | |
end | |
end | |
def create_tag name, contents, attrs, &block | |
if block | |
contents = contents.to_s << capture(&block).to_s | |
end | |
super | |
end | |
def capture &block | |
buffer = Base.new | |
buffer.instance_eval &block | |
buffer | |
end | |
end | |
include Tags | |
include Buffer | |
def menu attrs = {}, &block | |
tag :ul, attrs, &block | |
end | |
def menu_item name, attrs = {} | |
tag :li, tag(:a, :href => '/' + name.downcase), attrs | |
end | |
markup = menu do | |
menu_item 'Users' | |
menu_item 'Reports' | |
menu_item 'Content' | |
end | |
puts markup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment