Merb 0.9.5 select helper

I spent the last day helping to upgrade an application to Merb 0.9.5. There were a few problems with the select helper and we created this quick and dirty monkey patch to fix. Patch and tests to come.

module Merb::Helpers::Form::Builder
  class Base
    def update_bound_select(method, attrs)
      attrs[:value_method] ||= :to_s
      attrs[:text_method] ||= :to_s
      attrs[:selected] ||= @obj.send(attrs[:value_method])
    end

    def options(col, text_meth, value_meth, sel, b = nil)
      ([b] + col.map do |item|
        if item.is_a?(Hash) || item.is_a?(Array)
          text = item.last
          value = item.first
        elsif item.is_a?(String)
          text = text_meth ? item.send(text_meth) : item
          value = text_meth ? item.send(value_meth) : item
        else
          text = item.send(text_meth)
          value = item.send(value_meth)
        end

        option_attrs = {:value => value}
        option_attrs.merge!(:selected => "selected") if value == sel
        tag(:option, text, option_attrs)
      end).join
    end
  end
end

Leave a Reply