Module: ERBLint::Linters::Helpers

Included in:
ButtonComponentMigrationCounter, FlashComponentMigrationCounter
Defined in:
lib/primer/view_components/linters/helpers.rb

Overview

Helper methods for linting ERB.

Constant Summary collapse

SELF_CLOSING_TAGS =
%w[
  area base br col command embed hr input keygen
  link menuitem meta param source track wbr img
].freeze

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/primer/view_components/linters/helpers.rb', line 16

def self.included(base)
  base.include(ERBLint::LinterRegistry)

  define_method "run" do |processed_source|
    @offenses_not_corrected = 0
    tags = tags(processed_source)
    tag_tree = build_tag_tree(tags)

    tags.each do |tag|
      next if tag.closing?
      next unless self.class::TAGS&.include?(tag.name)

      classes = tag.attributes["class"]&.value&.split(" ") || []

      tag_tree[tag][:offense] = false

      next unless self.class::CLASSES.blank? || (classes & self.class::CLASSES).any?

      args = map_arguments(tag)
      correction = correction(args)

      tag_tree[tag][:offense] = true
      tag_tree[tag][:correctable] = !correction.nil?
      tag_tree[tag][:message] = message(args)
      tag_tree[tag][:correction] = correction
    end

    tag_tree.each do |tag, h|
      next unless h[:offense]

      # We always fix the offenses using blocks. The closing tag corresponds to `<% end %>`.
      if h[:correctable]
        add_offense(tag.loc, h[:message], h[:correction])
        add_offense(h[:closing].loc, h[:message], "<% end %>")
      else
        @offenses_not_corrected += 1
        generate_offense(self.class, processed_source, tag, h[:message])
      end
    end

    counter_correct?(processed_source)
  end

  define_method "autocorrect" do |processed_source, offense|
    return unless offense.context

    lambda do |corrector|
      if offense.context.include?(counter_disable)
        correct_counter(corrector, processed_source, offense)
      else
        corrector.replace(offense.source_range, offense.context)
      end
    end
  end
end