Class: ERBLint::Linters::CommentSyntax

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

Overview

Detects comment syntax that isn’t valid ERB.

Constant Summary

Constants included from ERBLint::LinterRegistry

ERBLint::LinterRegistry::CUSTOM_LINTERS_DIR

Instance Attribute Summary

Attributes inherited from ERBLint::Linter

#config, #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, #run_and_update_offense_status, support_autocorrect?

Constructor Details

#initialize(file_loader, config) ⇒ CommentSyntax

Returns a new instance of CommentSyntax.



9
10
11
# File 'lib/erb_lint/linters/comment_syntax.rb', line 9

def initialize(file_loader, config)
  super
end

Instance Method Details

#find_range(node, str) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/erb_lint/linters/comment_syntax.rb', line 42

def find_range(node, str)
  match = node.loc.source.match(Regexp.new(Regexp.quote(str.strip)))
  return unless match

  range_begin = match.begin(0) + node.loc.begin_pos
  range_end   = match.end(0) + node.loc.begin_pos
  (range_begin...range_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
# File 'lib/erb_lint/linters/comment_syntax.rb', line 13

def run(processed_source)
  file_content = processed_source.file_content
  return if file_content.empty?

  processed_source.ast.descendants(:erb).each do |erb_node|
    indicator_node, _, code_node, _ = *erb_node
    next if code_node.nil?

    indicator_node_str = indicator_node&.deconstruct&.last
    next if indicator_node_str == "#"

    code_node_str = code_node.deconstruct.last
    next unless code_node_str.start_with?(" #")

    range = find_range(erb_node, code_node_str)
    source_range = processed_source.to_source_range(range)

    correct_erb_tag = indicator_node_str == "=" ? "<%#=" : "<%#"

    add_offense(
      source_range,
      <<~EOF.chomp
        Bad ERB comment syntax. Should be #{correct_erb_tag} without a space between.
        Leaving a space between ERB tags and the Ruby comment character can cause parser errors.
      EOF
    )
  end
end