On Tue 21 May 2002 at 01:00:22 +0900, Wakou Aoyama wrote:

> On Tue, May 21, 2002 at 12:27:46AM +0900,
>  Tobias Reif wrote:
> 
> > Will it support XHTML1.0, which is the current version of HTML?
> 
> It may support XHTML1.0. Even if it will support HTML, it's String base.

I saw this as a great opportunity to try out Object#method_missing.

You can get a simple, yet quite effective method for handling any kind
of tag, by using the following interceptor method:

module HTML
  def method_missing(methId, data, attrs = {})
    tag = methId.id2name
    tag.upcase!
    attr_str = ''
    attrs.each do |key, value|
      attr_str << sprintf(' %s="%s"', key.upcase, value)
    end
    sprintf("<%s%s>%s</%s>", tag, attr_str, data, tag)
  end
end


You then call it like this:

require 'html'
include HTML

puts a('Google', 'href' => 'http://www.google.com/')
puts ul(li('item1') + li('item2') + li('item3'))


The output looks like this:

Google
<UL><LI>item1</LI><LI>item2</LI><LI>item3</LI></UL>
  
  
So how does it work?
  
You simply call the tag that you require as if it were a method in the
HTML module. However, no such method is defined, so Ruby invokes the
method_missing method to handle the error.
  
The method_missing method takes as its argument the original method's
symbol table name, followed by its arguments. The last argument is
optional and is a hash of attribute/value pairs, reflecting the
attributes common in so many HTML tags.

The method then converts the tag and attributes to upper-case, formats
the tag around its content, and ultimately returns it to the caller.

The thing that's remarkable about the above code is how brief it is
and how easy it was to write. It took me all of five minutes.
Obviously, it doesn't check for invalid tags and it could be improved
upon in other ways, but it surprised me how simple it was to do 90% of
the work.

This is probably all old hat to the gurus on this list, but for
someone who still considers himself a novice in the language, I was
very impressed by the ability to trap undefined methods like this.

Ian
-- 
Ian Macdonald               | Indifference will certainly be the downfall
ian / caliban.org             | of mankind, but who cares? 
                            | 
                            | 
                            |