aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb
blob: 60d017cfe57620b9630b4cd713bf9ab74226f508 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
module ActionView
  module Helpers
    module Tags
      class CollectionRadioButtons < CollectionSelect
        def render
          render_collection do |value, text, default_html_options|
            if block_given?
              yield sanitize_attribute_name(value), text, value, default_html_options
            else
              radio_button(value, default_html_options) +
                label(value, text, "collection_radio_buttons")
            end
          end
        end

        private

        def radio_button(value, html_options)
          @template_object.radio_button(@object_name, @method_name, value, html_options)
        end

        def label(value, text, css_class)
          @template_object.label(@object_name, sanitize_attribute_name(value), text, :class => css_class)
        end

        # Generate default options for collection helpers, such as :checked and
        # :disabled.
        def default_html_options_for_collection(item, value) #:nodoc:
          html_options = @html_options.dup

          [:checked, :selected, :disabled].each do |option|
            next unless @options[option]


            accept = if @options[option].respond_to?(:call)
                       @options[option].call(item)
                     else
                       Array(@options[option]).include?(value)
                     end

            if accept
              html_options[option] = true
            elsif option == :checked
              html_options[option] = false
            end
          end

          html_options
        end

        def sanitize_attribute_name(value) #:nodoc:
          "#{sanitized_method_name}_#{sanitized_value(value)}"
        end

        def render_collection #:nodoc:
          @collection.map do |item|
            value = value_for_collection(item, @value_method)
            text  = value_for_collection(item, @text_method)
            default_html_options = default_html_options_for_collection(item, value)

            yield value, text, default_html_options
          end.join.html_safe
        end

        def value_for_collection(item, value) #:nodoc:
          value.respond_to?(:call) ? value.call(item) : item.send(value)
        end
      end
    end
  end
end