Class: SyntaxTree::Tailwindcss::ErbMutationVisitor

Inherits:
ERB::MutationVisitor show all
Defined in:
lib/syntax_tree/tailwindcss/erb_mutation_visitor.rb

Instance Method Summary collapse

Methods inherited from ERB::MutationVisitor

#copy_and_visit_children, #visit

Constructor Details

#initialize(sorter) ⇒ ErbMutationVisitor

Returns a new instance of ErbMutationVisitor.



8
9
10
11
12
# File 'lib/syntax_tree/tailwindcss/erb_mutation_visitor.rb', line 8

def initialize(sorter)
  super()
  @sorter = sorter
  @ruby_visitor = SyntaxTree::Tailwindcss::RubyMutationVisitor.new(sorter)
end

Instance Method Details

#visit_attribute(node) ⇒ Object

Rewrite ‘class=“foo <%= something %> bar”`



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/syntax_tree/tailwindcss/erb_mutation_visitor.rb', line 22

def visit_attribute(node)
  clone = super
  return clone unless node.key.value == "class"
  return clone unless node.value.is_a?(SyntaxTree::ERB::HtmlString)

  contents =
    clone.value.contents.reject do |content|
      content.is_a?(SyntaxTree::ERB::Token) && content.type == :whitespace
    end

  clone.value.instance_variable_set(
    :@contents,
    contents.map.with_index do |content, index|
      next content unless content.is_a?(SyntaxTree::ERB::Token)

      # It's already a clone, so it's OK to mutate it
      new_value = @sorter.sort(content.value.split).join(" ")
      new_value = " #{new_value}" if index.positive? && erb_node?(contents[index - 1])
      new_value = "#{new_value} " if index < contents.size - 1 &&
        erb_node?(contents[index + 1])
      content.instance_variable_set(:@value, new_value)
      content
    end
  )

  clone
end

#visit_erb_content(node) ⇒ Object

Rewrite ‘<%= tag.span class: ’foo bar’ %>‘



15
16
17
18
19
# File 'lib/syntax_tree/tailwindcss/erb_mutation_visitor.rb', line 15

def visit_erb_content(node)
  node.dup.tap do |clone|
    clone.instance_variable_set(:@value, clone.value.accept(@ruby_visitor))
  end
end