Method: Primer::Classify::Utilities.classes_to_hash

Defined in:
lib/primer/classify/utilities.rb

.classes_to_hash(classes) ⇒ Object

Extract hash from classes ie. “mr-1 mb-2 foo” => { mr: 1, mb: 2, classes: “foo” }


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
# File 'lib/primer/classify/utilities.rb', line 95

def classes_to_hash(classes)
  obj = {}
  classes = classes.split
  # Loop through all classes supplied and reject ones we find a match for
  # So when we're at the end of the loop we have classes left with any non-system classes.
  classes.reject! do |classname|
    key, value, index = find_selector(classname)
    next false if key.nil?

    # Create array if nil
    obj[key] = Array.new(5, nil) if obj[key].nil?
    # Place the arguments in the responsive array based on index mr: [nil, 2]
    obj[key][index] = value
    next true
  end

  # Transform responsive arrays into arrays without trailing nil, so `mr: [1, nil, nil, nil, nil]` becomes `mr: 1`
  obj.transform_values! do |value|
    value = value.reverse.drop_while(&:nil?).reverse
    if value.count == 1
      value.first
    else
      value
    end
  end

  # Add back the non-system classes
  obj[:classes] = classes.join(" ") if classes.any?
  obj
end