Skip to content

Instantly share code, notes, and snippets.

@tj
Created June 29, 2009 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tj/137785 to your computer and use it in GitHub Desktop.
Save tj/137785 to your computer and use it in GitHub Desktop.
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