# = xmlhelper.rb
#
# == Copyright (c) 2006 Thomas Sawyer
#
#   Ruby License
#
#   This module is free software. You may use, modify, and/or redistribute this
#   software under the same terms as Ruby.
#
#   This program is distributed in the hope that it will be useful, but WITHOUT
#   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#   FOR A PARTICULAR PURPOSE.
#
# == Author(s)
#
# * Thomas Sawyer

# Author::    Thomas Sawyer
# Copyright:: Copyright (c) 2006 Thomas Sawyer
# License::   Ruby License

# = XMLHelper
#
# XMLHelper is a utility module which provides methods the ease the
# creation of XML markup.
#
# == Usage
#
#   x = XMLHelper
#   puts x.element( :a, x.element( :b, "X" ) )
#
# produces
#
#   <a><b>X</b></a>
#

module XMLHelper

  extend self

  # Empty XML document.

  def document( options )x
    doc = ''
    if options[:version]
      doc << xml( options[:version], options[:encoding] )
    end
  end
  alias_method :new, :document

  # XML declaration.

  def xml( version=nil, encoding=nil )
    atts = {}
    atts[:version] = version || '1.1'
    atts[:version] = encoding if encoding
    instruct( :xml, atts )
  end

  # Element.

  def element( tag, body=nil, atts={} )
    atts = atts.collect{ |k,v| %{ #{k}="#{v}"} }.join('')
    if body
      "<#{tag}#{atts}>#{body}</#{tag}>"
    else
      "<#{tag}#{atts} />"
    end
  end

  # Comment.

  def comment( remark )
    "<!-- #{remark} -->"
  end

  # Proccessing instruction.

  def instruct( tag, *args )
    atts = Hash === args.last ? args.pop : {}
    atts = atts.collect{ |k,v| %{ #{k}="#{v}"} }.join('')
    body = ' ' + args.join(' ')
    "<?#{tag}#{body}#{atts}?>"
  end
  alias_method :instruction, :instruct
  alias_method :pi, :instruct

  # Text.

  def text( str )
    str
  end

  # CData.

  def cdata( data )
    raise ArgumentError, "CDATA contains ']]>'" if data.index(']]>')
    "<![CDATA[#{data}]]>"
  end

  # DOCTYPE DTD declaration.

  def doctype!( *args )
    "<!DOCTYPE"
  end

  # ELEMENT DTD declaration.

  def element!( *args )
    '<!ELEMENT'
  end

  # ATTLIST DTD declaration.

  def attlist!( *args )
    '<!ATTLIST'
  end

  # ENTITY DTD declaration.

  def entity!( *args )
    '<!ENTITY'
  end

  # NOTATION DTD declaration.

  def notation!( *args )
    '<!NOTATION'
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#

=begin test

  require 'test/unit'

  class TCXMLHelper < Test::Unit::TestCase

    def test_01
      x = XMLHelper
      d = x.element( :a )
      assert_equal( "<a />", d )
    end

    def test_02
      x = XMLHelper
      d = x.element( :a, x.element( :b, "X" ) )
      assert_equal( "<a><b>X</b></a>", d )
    end

    def test_03
      x = XMLHelper
      d = x.element( :a, x.element( :b, "X" ) + x.element( :c, "Y" ) )
      assert_equal( "<a><b>X</b><c>Y</c></a>", d )
    end

  end

=end
