Skip to content

Instantly share code, notes, and snippets.

@tj tj/example.rb
Created Jun 29, 2009

Embed
What would you like to do?
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
You can’t perform that action at this time.