require 'nitro/builder/xml'
module Nitro
# A helper mixin for programmatically building XHTML
# blocks.
module XhtmlBuilderMixin
# Render select.
#
# The first argument can be a String denoting the
# default option.
#--
# gmosx: hmmm String defines select, this is bad!
#++
def select(*args)
attrs = args.last.is_a?(Hash) ? args.pop : nil
start_tag!('select', attrs)
self << %|| unless args.empty?
yield
end_tag!('select')
end
# Render select options.
#
# [+opts+]
# The options to render, can be an Array or a
# Hash (allows you to explicitly set the value
# mapping).
#
# [+selected+]
# The value of the selected option.
#
# == Example
#
# options = ['Male', 'Female']
# o.select(:name => 'sex') {
# o.options(options, selected = 1)
# }
#
# or
#
# options = { 'Male' => 'm', 'Female' => 'f' }
# o.select(:name => 'sex') {
# o.options(options, selected = 1)
# }
def options(opts, selected = nil)
if opts.is_a?(Array)
selected = selected.to_i
opts.each_with_index do |label, value|
if value == selected
self << %||
else
self << %||
end
end
else
opts.each do |label, value|
if value == selected
self << %||
else
self << %||
end
end
end
end
def submit(options = nil)
if options
opts = options.collect { |k, v| %[#{k}="#{v}"] }.join(' ')
self << %[]
else
self << %||
end
end
end
# A String extension with XHTML generation
# functionality.
class XhtmlString < String
include XmlBuilderMixin
include XhtmlBuilderMixin
end
# A class that encapsulats the XHTML generation
# functionality. Utilizes duck typing to redirect
# output to a target buffer.
class XhtmlBuilder
include XmlBuilderMixin
include XhtmlBuilderMixin
# The target receives the generated xml,
# should respond_to :<<
attr_accessor :target
def initialize(target = '')
@target = target
end
def << (str)
@target << str
end
def to_s
@target.to_s
end
end
end
# * George Moschovitis
__END__
{