File: style_attribute_builder.rb

package info (click to toggle)
ruby-roadie 5.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 528 kB
  • sloc: ruby: 3,418; makefile: 5
file content (28 lines) | stat: -rw-r--r-- 714 bytes parent folder | download | duplicates (3)
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
# frozen_string_literal: true

module Roadie
  class StyleAttributeBuilder
    def initialize
      @styles = []
    end

    def <<(style)
      @styles << style
    end

    def attribute_string
      Deduplicator.apply(stable_sort(@styles).map(&:to_s)).join(";")
    end

    private

    def stable_sort(list)
      # Ruby's sort is unstable for performance reasons. We need it to be
      # stable, e.g. to preserve order of elements that are compared equal in
      # the sorting.
      # We can accomplish this by using the original array index as a second
      # comparator for when the first one is equal.
      list.each_with_index.sort_by { |item, index| [item, index] }.map(&:first)
    end
  end
end