Class: SorbetErb::CodeProcessor

Inherits:
Object
  • Object
show all
Includes:
AST::Processor::Mixin
Defined in:
lib/sorbet_erb/code_extractor.rb

Constant Summary collapse

LOCALS_PREFIX =
'locals:'
LOCALS_SIG_PREFIX =
'locals_sig:'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCodeProcessor

Returns a new instance of CodeProcessor.



29
30
31
32
33
# File 'lib/sorbet_erb/code_extractor.rb', line 29

def initialize
  @output = []
  @locals = nil
  @locals_sig = nil
end

Instance Attribute Details

#localsObject

Returns the value of attribute locals.



27
28
29
# File 'lib/sorbet_erb/code_extractor.rb', line 27

def locals
  @locals
end

#locals_sigObject

Returns the value of attribute locals_sig.



27
28
29
# File 'lib/sorbet_erb/code_extractor.rb', line 27

def locals_sig
  @locals_sig
end

#outputObject

Returns the value of attribute output.



27
28
29
# File 'lib/sorbet_erb/code_extractor.rb', line 27

def output
  @output
end

Instance Method Details

#handler_missing(node) ⇒ Object



35
36
37
38
39
# File 'lib/sorbet_erb/code_extractor.rb', line 35

def handler_missing(node)
  # Some children may be strings, so only look for AST nodes
  children = node.children.select { |c| c.is_a?(BetterHtml::AST::Node) }
  process_all(children)
end

#on_code(node) ⇒ Object



63
64
65
# File 'lib/sorbet_erb/code_extractor.rb', line 63

def on_code(node)
  @output += node.children
end

#on_erb(node) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/sorbet_erb/code_extractor.rb', line 41

def on_erb(node)
  indicator_node = node.children.compact.find { |c| c.type == :indicator }
  code_node = node.children.compact.find { |c| c.type == :code }

  return process(code_node) if indicator_node.nil?

  indicator = indicator_node.children.first
  case indicator
  when '#'
    # Ignore comments if it's not strict locals
    code_text = code_node.children.first.strip
    if code_text.start_with?(LOCALS_PREFIX)
      # No need to parse the locals
      @locals = code_text.delete_prefix(LOCALS_PREFIX).strip
    elsif code_text.start_with?(LOCALS_SIG_PREFIX)
      @locals_sig = code_text.delete_prefix(LOCALS_SIG_PREFIX).strip
    end
  else
    process_all(node.children)
  end
end