Class: Forme::Labeler::Explicit

Inherits:
Object
  • Object
show all
Defined in:
lib/forme/transformers/labeler.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.


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
# File 'lib/forme/transformers/labeler.rb', line 52

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