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.

Defined Under Namespace

Classes: ConfigSchema

Constant Summary collapse

SELF_CLOSING_TAGS =
["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

clear, find_by_name, included, linters, 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



49
50
51
52
53
# File 'lib/erb_lint/linters/self_closing_tag.rb', line 49

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

#run(processed_source) ⇒ Object



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
# File 'lib/erb_lint/linters/self_closing_tag.rb', line 17

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 a void element, it must not start with `</`.",
        ""
      )
    end

    if @config.enforced_style == :always && !tag.self_closing?
      add_offense(
        tag_node.loc.end.offset(-1),
        "Tag `#{tag.name}` is self-closing, it must end with `/>`.",
        "/"
      )
    end

    next unless @config.enforced_style == :never && tag.self_closing?
    end_solidus = tag_node.children.last
    add_offense(
      end_solidus.loc,
      "Tag `#{tag.name}` is a void element, it must end with `>` and not `/>`.",
      ""
    )
  end
end