select.rb 1.2 KB
Newer Older
R
Rafael Mendonça França 已提交
1 2
module ActionView
  module Helpers
3 4
    module Tags # :nodoc:
      class Select < Base # :nodoc:
R
Rafael Mendonça França 已提交
5
        def initialize(object_name, method_name, template_object, choices, options, html_options)
6
          @choices = block_given? ? template_object.capture { yield || "" } : choices
7
          @choices = @choices.to_a if @choices.is_a?(Range)
8

R
Rafael Mendonça França 已提交
9 10 11 12 13 14
          @html_options = html_options

          super(object_name, method_name, template_object, options)
        end

        def render
15
          option_tags_options = {
16 17
            selected: @options.fetch(:selected) { value(@object) },
            disabled: @options[:disabled]
18
          }
R
Rafael Mendonça França 已提交
19

20 21
          option_tags = if grouped_choices?
            grouped_options_for_select(@choices, option_tags_options)
R
Rafael Mendonça França 已提交
22
          else
23
            options_for_select(@choices, option_tags_options)
R
Rafael Mendonça França 已提交
24 25 26 27
          end

          select_content_tag(option_tags, @options, @html_options)
        end
28 29 30

        private

31 32 33 34
          # Grouped choices look like this:
          #
          #   [nil, []]
          #   { nil => [] }
35
          def grouped_choices?
36
            !@choices.blank? && @choices.first.respond_to?(:last) && Array === @choices.first.last
37
          end
R
Rafael Mendonça França 已提交
38 39 40 41
      end
    end
  end
end