Class: Solargraph::Rails::Delegate

Inherits:
Object
  • Object
show all
Defined in:
lib/solargraph/rails/delegate.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.instanceObject



6
7
8
# File 'lib/solargraph/rails/delegate.rb', line 6

def self.instance
  @instance ||= self.new
end

.supported?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/solargraph/rails/delegate.rb', line 10

def self.supported?
  Solargraph::Pin.const_defined?(:DelegatedMethod)
end

Instance Method Details

#process(source_map, ns) ⇒ Object



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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/solargraph/rails/delegate.rb', line 14

def process(source_map, ns)
  return [] unless self.class.supported?
  return [] unless source_map.code.include?('delegate')

  walker = Walker.from_source(source_map.source)
  pins = []

  walker.on :send, [nil, :delegate] do |ast|
    last_child = ast.children[-1]
    next unless last_child.instance_of?(::Parser::AST::Node) && last_child.type == :hash

    methods = ast.children[2...-1].select { |c| c.type == :sym }

    delegate_node = Util.extract_option(ast, :to)
    next unless delegate_node

    chain = if delegate_node.type == :sym
      # `delegate ..., to: :bar` means call the #bar method to get the delegate object
      call = Solargraph::Source::Chain::Call.new(delegate_node.children[0].to_s)
      Solargraph::Source::Chain.new([call], delegate_node)
    else
      # for any other type of delegate, we create a chain from the AST node
      Solargraph::Parser::Legacy::NodeChainer.chain(delegate_node, ns.filename)
    end

    prefix_node = Util.extract_option(ast, :prefix)

    prefix = nil
    if prefix_node
      if prefix_node.type == :sym
        prefix = prefix_node.children[0]
      elsif prefix_node.type == :true && delegate_node.type == :sym
        prefix = delegate_node.children[0]
      end
    end

    location = Util.build_location(delegate_node, ns.filename)
    methods.each do |meth|
      method_name = meth.children[0]
      pins << Solargraph::Pin::DelegatedMethod.new(
        closure: ns,
        scope: :instance,
        name: [prefix, method_name].select(&:itself).join("_"),
        node: meth,
        receiver: chain,
        receiver_method_name: method_name.to_s,
      )
    end
  end

  walker.walk

  if pins.any?
    Solargraph.logger.debug(
      "[Rails][Delegate] added #{pins.map(&:name)} to #{ns.path}"
    )
  end

  pins
end