File: attribute_merger.rb

package info (click to toggle)
ruby-temple 0.10.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 476 kB
  • sloc: ruby: 3,347; makefile: 6
file content (43 lines) | stat: -rw-r--r-- 1,388 bytes parent folder | download | duplicates (2)
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
# frozen_string_literal: true
module Temple
  module HTML
    # This filter merges html attributes (e.g. used for id and class)
    # @api public
    class AttributeMerger < Filter
      define_options merge_attrs: {'id' => '_', 'class' => ' '}

      def on_html_attrs(*attrs)
        values = {}

        attrs.each do |_, _, name, value|
          name = name.to_s
          if values[name]
            raise(FilterError, "Multiple #{name} attributes specified") unless options[:merge_attrs][name]
            values[name] << value
          else
            values[name] = [value]
          end
        end

        attrs = values.map do |name, value|
          if (delimiter = options[:merge_attrs][name]) && value.size > 1
            exp = [:multi]
            if value.all? {|v| contains_nonempty_static?(v) }
              exp << value.first
              value[1..-1].each {|v| exp << [:static, delimiter] << v }
            else
              captures = unique_name
              exp << [:code, "#{captures} = []"]
              value.each_with_index {|v, i| exp << [:capture, "#{captures}[#{i}]", v] }
              exp << [:dynamic, "#{captures}.reject(&:empty?).join(#{delimiter.inspect})"]
            end
          else
            exp = value.first
          end
          [:html, :attr, name, exp]
        end
        [:html, :attrs, *attrs]
      end
    end
  end
end