Class: Rubocop::Cop::Style::Lambda

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/style/lambda.rb

Overview

This cop checks for uses of the pre 1.9 lambda syntax for one-line anonymous functions and uses of the 1.9 lambda syntax for multi-line anonymous functions.

Constant Summary collapse

SINGLE_MSG =
'Use the new lambda literal syntax ->(params) {...}.'
MULTI_MSG =
'Use the lambda method for multi-line lambdas.'
TARGET =
s(:send, nil, :lambda)

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods inherited from Cop

#add_offence, #autocorrect_action, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, #inspect, lint?, #name, rails?, style?

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#on_block(node) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rubocop/cop/style/lambda.rb', line 15

def on_block(node)
  # We're looking for
  # (block
  #   (send nil :lambda)
  #   ...)
  block_method, = *node

  if block_method == TARGET
    selector = block_method.loc.selector.source
    lambda_length = lambda_length(node)

    if selector != '->' && lambda_length == 0
      add_offence(:convention, block_method.loc.expression, SINGLE_MSG)
    elsif selector == '->' && lambda_length > 0
      add_offence(:convention, block_method.loc.expression, MULTI_MSG)
    end
  end

  super
end