Class: Forme::Labeler::Explicit

Inherits:
Object
  • Object
show all
Defined in:
lib/forme.rb

Overview

Explicit labeler that creates a separate label tag that references the given tag’s id using a for attribute. Requires that all tags with labels have id fields.

Registered as :explicit.

Instance Method Summary collapse

Instance Method Details

#call(tag, input) ⇒ Object

Return an array with a label tag as the first entry and tag as a second entry. If the input has a :label_for option, use that, otherwise use the input’s :id option. If neither the :id or :label_for option is used, the label created will not be associated with an input.



1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
# File 'lib/forme.rb', line 1163

def call(tag, input)
  unless id = input.opts[:id]
    if key = input.opts[:key]
      namespaces = input.form_opts[:namespace]
      id = "#{namespaces.join('_')}#{'_' unless namespaces.empty?}#{key}"
      if key_id = input.opts[:key_id]
        id << "_#{key_id.to_s}"
      end
    end
  end

  label_attr = input.opts[:label_attr]
  label_attr = label_attr ? label_attr.dup : {}
  label_attr[:for] ||= input.opts.fetch(:label_for, id)
  lpos = input.opts[:label_position] || ([:radio, :checkbox].include?(input.type) ? :after : :before)

  Forme.attr_classes(label_attr, "label-#{lpos}")
  label = input.tag(:label, label_attr, [input.opts[:label]])

  t = if lpos == :before
    [label, tag]
  else
    [tag, label]
  end

  t
end