aboutsummaryrefslogtreecommitdiffstats
path: root/actionview/lib/action_view/helpers/tags/base.rb
blob: dec1c1f0706f2a16538155d922c3569eca1edcc6 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# frozen_string_literal: true
module ActionView
  module Helpers
    module Tags # :nodoc:
      class Base # :nodoc:
        include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper
        include FormOptionsHelper

        attr_reader :object

        def initialize(object_name, method_name, template_object, options = {})
          @object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
          @template_object = template_object

          @object_name.sub!(/\[\]$/, "") || @object_name.sub!(/\[\]\]$/, "]")
          @object = retrieve_object(options.delete(:object))
          @skip_default_ids = options.delete(:skip_default_ids)
          @allow_method_names_outside_object = options.delete(:allow_method_names_outside_object)
          @options = options

          if Regexp.last_match
            @generate_indexed_names = true
            @auto_index = retrieve_autoindex(Regexp.last_match.pre_match)
          else
            @generate_indexed_names = false
            @auto_index = nil
          end
        end

        # This is what child classes implement.
        def render
          raise NotImplementedError, "Subclasses must implement a render method"
        end

        private

          def value(object)
            if @allow_method_names_outside_object
              object.public_send @method_name if object && object.respond_to?(@method_name)
            else
              object.public_send @method_name if object
            end
          end

          def value_before_type_cast(object)
            unless object.nil?
              method_before_type_cast = @method_name + "_before_type_cast"

              if value_came_from_user?(object) && object.respond_to?(method_before_type_cast)
                object.public_send(method_before_type_cast)
              else
                value(object)
              end
            end
          end

          def value_came_from_user?(object)
            method_name = "#{@method_name}_came_from_user?"
            !object.respond_to?(method_name) || object.public_send(method_name)
          end

          def retrieve_object(object)
            if object
              object
            elsif @template_object.instance_variable_defined?("@#{@object_name}")
              @template_object.instance_variable_get("@#{@object_name}")
            end
          rescue NameError
            # As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil.
            nil
          end

          def retrieve_autoindex(pre_match)
            object = self.object || @template_object.instance_variable_get("@#{pre_match}")
            if object && object.respond_to?(:to_param)
              object.to_param
            else
              raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
            end
          end

          def add_default_name_and_id_for_value(tag_value, options)
            if tag_value.nil?
              add_default_name_and_id(options)
            else
              specified_id = options["id"]
              add_default_name_and_id(options)

              if specified_id.blank? && options["id"].present?
                options["id"] += "_#{sanitized_value(tag_value)}"
              end
            end
          end

          def add_default_name_and_id(options)
            index = name_and_id_index(options)
            options["name"] = options.fetch("name") { tag_name(options["multiple"], index) }

            unless skip_default_ids?
              options["id"] = options.fetch("id") { tag_id(index) }
              if namespace = options.delete("namespace")
                options["id"] = options["id"] ? "#{namespace}_#{options['id']}" : namespace
              end
            end
          end

          def tag_name(multiple = false, index = nil)
            # a little duplication to construct less strings
            case
            when @object_name.empty?
              "#{sanitized_method_name}#{"[]" if multiple}"
            when index
              "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}"
            else
              "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}"
            end
          end

          def tag_id(index = nil)
            # a little duplication to construct less strings
            case
            when @object_name.empty?
              sanitized_method_name.dup
            when index
              "#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
            else
              "#{sanitized_object_name}_#{sanitized_method_name}"
            end
          end

          def sanitized_object_name
            @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
          end

          def sanitized_method_name
            @sanitized_method_name ||= @method_name.sub(/\?$/, "")
          end

          def sanitized_value(value)
            value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase
          end

          def select_content_tag(option_tags, options, html_options)
            html_options = html_options.stringify_keys
            add_default_name_and_id(html_options)

            if placeholder_required?(html_options)
              raise ArgumentError, "include_blank cannot be false for a required field." if options[:include_blank] == false
              options[:include_blank] ||= true unless options[:prompt]
            end

            value = options.fetch(:selected) { value(object) }
            select = content_tag("select", add_options(option_tags, options, value), html_options)

            if html_options["multiple"] && options.fetch(:include_hidden, true)
              tag("input", disabled: html_options["disabled"], name: html_options["name"], type: "hidden", value: "") + select
            else
              select
            end
          end

          def placeholder_required?(html_options)
            # See https://html.spec.whatwg.org/multipage/forms.html#attr-select-required
            html_options["required"] && !html_options["multiple"] && html_options.fetch("size", 1).to_i == 1
          end

          def add_options(option_tags, options, value = nil)
            if options[:include_blank]
              option_tags = tag_builder.content_tag_string("option", options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, value: "") + "\n" + option_tags
            end
            if value.blank? && options[:prompt]
              option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), value: "") + "\n" + option_tags
            end
            option_tags
          end

          def name_and_id_index(options)
            if options.key?("index")
              options.delete("index") || ""
            elsif @generate_indexed_names
              @auto_index || ""
            end
          end

          def skip_default_ids?
            @skip_default_ids
          end
      end
    end
  end
end