Class: RuboCop::Cop::Homebrew::MultilineMethodChain Private

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
rubocops/multiline_method_chain.rb

Overview

This class is part of a private API. This class may only be used in the Homebrew/brew repository. Third parties should avoid using this class if possible, as it may be removed or changed without warning.

Keeps one dotted call per line when a method chain is split.

Examples:

# bad
dependents.keys.to_set
          .merge(other)

# good
dependents.keys.to_set.merge(other)
dependents.keys
          .to_set
          .merge(other)

Constant Summary collapse

MSG =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"Start each call in a multiline chain on its own line."

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ void Also known as: on_csend

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


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
# File 'rubocops/multiline_method_chain.rb', line 25

def on_send(node)
  return if node.single_line? || (node.block_node || node).chained?

  dots = T.let([], T::Array[Parser::Source::Range])
  call = T.let(node, T.nilable(RuboCop::AST::Node))
  while call.is_a?(RuboCop::AST::SendNode)
    dots << call.loc.dot if call.dot? || call.safe_navigation?
    call = call.receiver
    call = call.send_node if call.is_a?(RuboCop::AST::BlockNode)
  end
  dots.reverse!
  continuation = dots.find(&:begins_its_line?)
  return unless continuation

  dots.drop(1).each do |dot|
    next if dot.begins_its_line?
    # A newline after a heredoc opener would put the call inside the string.
    next if processed_source.ast.each_node(:any_str).any? do |str|
      str.heredoc? && str.first_line == dot.line && str.source_range.begin_pos < dot.begin_pos
    end

    add_offense(dot) do |corrector|
      corrector.insert_before(dot, "\n#{" " * continuation.column}")
    end
  end
end