Class: ERBLint::Linters::SuperInComponentTemplates

Inherits:
Linter
  • Object
show all
Includes:
ERBLint::LinterRegistry, Helpers::RubocopHelpers
Defined in:
lib/yattho/view_components/linters/super_in_component_templates.rb

Overview

Replaces calls to ‘super` with calls to `render_parent`.

Instance Method Summary collapse

Methods included from Helpers::RubocopHelpers

#erb_ast

Instance Method Details

#autocorrect(_, offense) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/yattho/view_components/linters/super_in_component_templates.rb', line 46

def autocorrect(_, offense)
  return unless offense.context

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

#run(processed_source) ⇒ Object



12
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
# File 'lib/yattho/view_components/linters/super_in_component_templates.rb', line 12

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

    super_call_nodes = find_super_call_nodes(ast)
    next if super_call_nodes.empty?

    indicator, = *indicator_node
    indicator ||= ""

    # +2 to account for the leading "<%" characters
    code_start_pos = erb_node.location.begin_pos + indicator.size + 2

    super_call_nodes.each do |super_call_node|
      orig_loc = code_node.location
      super_call_loc = super_call_node.location.expression

      new_loc = orig_loc.with(
        begin_pos: super_call_loc.begin_pos + code_start_pos,
        end_pos: super_call_loc.end_pos + code_start_pos
      )

      add_offense(
        new_loc,
        "Avoid calling `super` in component templates. Call `render_parent` instead",
        "render_parent"
      )
    end
  end
end