Class: ERBLint::Linters::SelfClosingTag

Inherits:
ERBLint::Linter show all
Includes:
ERBLint::LinterRegistry
Defined in:
lib/erb_lint/linters/self_closing_tag.rb

Overview

Warns when a tag is not self-closed properly.

Constant Summary collapse

SELF_CLOSING_TAGS =
%w(
  area base br col command embed hr input keygen
  link menuitem meta param source track wbr img
)

Constants included from ERBLint::LinterRegistry

ERBLint::LinterRegistry::CUSTOM_LINTERS_DIR

Instance Attribute Summary

Attributes inherited from ERBLint::Linter

#offenses

Instance Method Summary collapse

Methods included from ERBLint::LinterRegistry

find_by_name, included, load_custom_linters

Methods inherited from ERBLint::Linter

#add_offense, #clear_offenses, #enabled?, #excludes_file?, inherited, #initialize, support_autocorrect?

Constructor Details

This class inherits a constructor from ERBLint::Linter

Instance Method Details

#autocorrect(_processed_source, offense) ⇒ Object



37
38
39
40
41
# File 'lib/erb_lint/linters/self_closing_tag.rb', line 37

def autocorrect(_processed_source, offense)
  lambda do |corrector|
    corrector.replace(offense.source_range, offense.context)
  end
end

#run(processed_source) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/erb_lint/linters/self_closing_tag.rb', line 14

def run(processed_source)
  processed_source.ast.descendants(:tag).each do |tag_node|
    tag = BetterHtml::Tree::Tag.from_node(tag_node)
    next unless SELF_CLOSING_TAGS.include?(tag.name)

    if tag.closing?
      start_solidus = tag_node.children.first
      add_offense(
        start_solidus.loc,
        "Tag `#{tag.name}` is self-closing, it must not start with `</`.",
        ''
      )
    end

    next if tag.self_closing?
    add_offense(
      tag_node.loc.end.offset(-1),
      "Tag `#{tag.name}` is self-closing, it must end with `/>`.",
      '/'
    )
  end
end