From: Chris Pine Date: 2005-04-19T14:10:03+09:00 Subject: Re: Html Tag Generation I use a pretty low-tech trick myself, but it works pretty well. Just a few methods and a couple of variables: @page = [] @depth = 0 # Outputs string to page being generated. def puts string @page << ' '*@depth+string end # Plain old paragraph. def para (attributes = {}, &block) method_missing(:p, attributes, &block) end # Centered paragraph. def parac (attributes = {}, &block) attributes[:style] = 'text-align: center' para(attributes, &block) end # Makes a generic tag; I never defined the "html" method, # or "head" or "body" or "h1" or "br"... so they all use # this code to build the appropriate tag. (I couldn't do # this with the "p" tag, since "p" *is* defined as a method # so I used "para" and "parac" above. def method_missing (methodSymbol, attributes = {}) methodName = methodSymbol.to_s attribString = '' attributes.each do |key, val| raise methodName+' '+attributes.inspect if (key.nil? || val.nil?) attribString += ' '+key.to_s+'="'+val+'"' end if (!block_given?) puts '<'+methodName+attribString+' />' else puts '<'+methodName+attribString+'>' @depth += 1 blockReturn = yield puts blockReturn if (blockReturn.kind_of?(String)) @depth -= 1 puts '' end nil end This does a pretty good job of making readable html. To use it: html do head do link(:rel=>'stylesheet', :type=>'text/css', :href=>'local.css') title do 'pine.fm — ' + theTitle end end body do div(:id=>'headerBar') do ... and so on. You can, of course, use {,} instead of do,end. It also allows for
style tags by calling the tag with a string instead of a block. Nothing too fancy, but it serves me well, Chris