Class: ERBLint::Linters::StrictLocals

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

Overview

Enforces the use of strict locals in Rails view partial templates.

Constant Summary collapse

STRICT_LOCALS_REGEX =
/\s+locals:\s+\((.*)\)/

Constants included from ERBLint::LinterRegistry

ERBLint::LinterRegistry::CUSTOM_LINTERS_DIR, ERBLint::LinterRegistry::DEPRECATED_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) ⇒ StrictLocals

Returns a new instance of StrictLocals.



11
12
13
# File 'lib/erb_lint/linters/strict_locals.rb', line 11

def initialize(file_loader, config)
  super
end

Instance Method Details

#autocorrect(_processed_source, offense) ⇒ Object



43
44
45
46
47
# File 'lib/erb_lint/linters/strict_locals.rb', line 43

def autocorrect(_processed_source, offense)
  lambda do |corrector|
    corrector.insert_before(offense.source_range, "<%# locals: () %>\n")
  end
end

#run(processed_source) ⇒ Object



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

def run(processed_source)
  return unless processed_source.filename.match?(%r{(\A|.*/)_[^/\s]*\.html\.erb\z})

  file_content = processed_source.file_content
  return if file_content.empty?

  strict_locals_node = processed_source.ast.descendants(:erb).find do |erb_node|
    indicator_node, _, code_node, _ = *erb_node

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

    code_node_str = code_node&.deconstruct&.last

    code_node_str.match(STRICT_LOCALS_REGEX)
  end

  unless strict_locals_node
    add_offense(
      processed_source.to_source_range(0...processed_source.file_content.size),
      <<~EOF.chomp,
        Missing strict locals declaration.
        Add <%# locals: () %> at the top of the file to enforce strict locals.
      EOF
    )
  end
end