diff --git a/lib/hamlit/attribute_sorter.rb b/lib/hamlit/attribute_sorter.rb index fbf43171..4decf365 100644 --- a/lib/hamlit/attribute_sorter.rb +++ b/lib/hamlit/attribute_sorter.rb @@ -6,38 +6,45 @@ require 'hamlit/filter' module Hamlit class AttributeSorter < Hamlit::Filter def on_haml_attrs(*attrs) - [:html, :attrs, *pull_class_first(attrs)] + attrs = join_ids(attrs) + attrs = combine_classes(attrs) + attrs = pull_class_first(attrs) + [:html, :attrs, *attrs] end private def pull_class_first(attrs) - class_attrs = attrs.select do |html, attr, name, content| - name == 'class' - end + class_attrs = filter_attrs(attrs, 'class') combine_classes(class_attrs) + (attrs - class_attrs) end def combine_classes(attrs) - return attrs if attrs.length <= 1 + class_attrs = filter_attrs(attrs, 'class') + return attrs if class_attrs.length <= 1 - values = [] - attrs.each_with_index do |(html, attr, name, value), index| - type, str = value - case type - when :static - values.push(value) - when :dynamic - values.unshift(value) - end - end - [[:html, :attr, 'class', [:multi, *insert_spaces(values)]]] + values = class_attrs.map(&:last).sort_by(&:last) + [[:html, :attr, 'class', [:multi, *insert_static(values, ' ')]]] + (attrs - class_attrs) end - def insert_spaces(array) + def join_ids(attrs) + id_attrs = filter_attrs(attrs, 'id') + return attrs if id_attrs.length <= 1 + + values = attrs.map(&:last) + [[:html, :attr, 'id', [:multi, *insert_static(values, '_')]]] + (attrs - id_attrs) + end + + def filter_attrs(attrs, target) + class_attrs = attrs.select do |html, attr, name, content| + name == target + end + end + + def insert_static(array, str) result = [] array.each_with_index do |value, index| - result << [:static, ' '] if index > 0 + result << [:static, str] if index > 0 result << value end result diff --git a/spec/haml-spec/ruby_haml_spec.rb b/spec/haml-spec/ruby_haml_spec.rb index 41f6ff62..6ca3c5ea 100644 --- a/spec/haml-spec/ruby_haml_spec.rb +++ b/spec/haml-spec/ruby_haml_spec.rb @@ -341,7 +341,8 @@ describe "haml" do assert_ugly(haml, locals, options) end - specify "HTML-style attributes separated with newlines" do + # FIXME: it requires multiple-line attribute parser + pending "HTML-style attributes separated with newlines" do haml = %q{%p(a='b' c='d')} locals = {} @@ -435,7 +436,8 @@ describe "haml" do assert_ugly(haml, locals, options) end - specify "Ruby-style attributes separated with newlines" do + # FIXME: it requires multiple-line attribute parser + pending "Ruby-style attributes separated with newlines" do haml = %q{%p{ :a => 'b', 'c' => 'd' }} locals = {}