Class: ERBLint::Linters::ClosingErbTagIndent

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

Overview

When ‘<%` isn’t followed by a newline, ensure ‘%>` isn’t preceeded by a newline. When ‘%>` is preceeded by a newline, indent it at the same level as the corresponding `<%`.

Constant Summary collapse

START_SPACES =
/\A([[:space:]]*)/m
END_SPACES =
/([[:space:]]*)\z/m

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



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

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

#run(processed_source) ⇒ Object



13
14
15
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
# File 'lib/erb_lint/linters/closing_erb_tag_indent.rb', line 13

def run(processed_source)
  processed_source.ast.descendants(:erb).each do |erb_node|
    _, _, code_node, = *erb_node
    code = code_node.children.first

    start_spaces = code.match(START_SPACES)&.captures&.first || ""
    end_spaces = code.match(END_SPACES)&.captures&.first || ""

    start_with_newline = start_spaces.include?("\n")
    end_with_newline = end_spaces.include?("\n")

    if !start_with_newline && end_with_newline
      add_offense(
        code_node.loc.end.adjust(begin_pos: -end_spaces.size),
        "Remove newline before `%>` to match start of tag.",
        ' '
      )
    elsif start_with_newline && !end_with_newline
      add_offense(
        code_node.loc.end.adjust(begin_pos: -end_spaces.size),
        "Insert newline before `%>` to match start of tag.",
        "\n"
      )
    elsif start_with_newline && end_with_newline
      current_indent = end_spaces.split("\n", -1).last
      if erb_node.loc.column != current_indent.size
        add_offense(
          code_node.loc.end.adjust(begin_pos: -current_indent.size),
          "Indent `%>` on column #{erb_node.loc.column} to match start of tag.",
          ' ' * erb_node.loc.column
        )
      end
    end
  end
end