Berger, Daniel
1/13/2006 7:55:00 PM
Paul Duncan wrote:
> * Daniel Berger (Daniel.Berger@qwest.com) wrote:
>
>>Hi all,
>>
>>Is there something out there that would let me create DOM objects in a more
>>Rubyesque manner? For example, say I want to create a 'select' object in a
>>web page. I'd like an API something along these lines:
>>
>>select = Select.new
>>select.options = ["joe", "bob", "moe"] # or {1=>"joe", 2=>"bob", 3=>"moe"}
>>select.selected_index = 2
>>select.title = "Three guys"
>>select.access_key = "A"
>>
>>p select.html # Show html that would be generated using above options
>>
>>You get the picture. Is there anything like this out on the RAA? Nothing
>>immediately jumped out at me.
>
>
> REXML has a DOM-like API, and it comes pre-installed with Ruby:
>
> # load REXML
> require 'rexml/document'
>
> #
> # Create an HTML select element.
> #
> class HTMLSelect
> attr_accessor :options, :attrs, :index
>
> def initialize(options = [], select_attrs = {}, selected_index = nil)
> @options, @attrs, @index = options, select_attrs, selected_index
> end
>
> def to_s
> # create return select element and append requested attributes
> ret = REXML::Element.new('select')
> @attrs.each { |key, val| ret.attributes[key] = val }
>
> # iterate over, create, and append each option
> @options.each_with_index do |opt, i|
> # create and append element
> opt_elem = ret << REXML::Element.new('option')
>
> # add option text, and option attributes
> opt_elem << REXML::Text.new(opt)
> opt_elem.attributes['value'] = i.to_s
> opt_elem.attributes['selected'] = 'Y' if i == @index
> end
>
> # convert select element to string and return
> ret.to_s
> end
> end
>
> # define attributes, option items, and initial selected index
> select_attrs = {
> 'name' => 'which_guy',
> 'title' => 'Three Guys',
> 'access_key' => 'A',
> }
> selected_index, options = 2, %w{joe bob moe}
>
> # build select box and print out result
> puts HTMLSelect.new(options, select_attrs, selected_index).to_s
>
> Hope this helps...
>
Ah, thanks Paul. I'd like something prebuilt, but it looks like REXML would
serve as a great way to build things behind the scenes.
Regards,
Dan