lib/rubocop/cop/style/lambda.rb in rubocop-0.37.2 vs lib/rubocop/cop/style/lambda.rb in rubocop-0.38.0
- old
+ new
@@ -6,12 +6,10 @@
module Style
# 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.
class Lambda < Cop
- include AutocorrectUnlessChangingAST
-
SINGLE_MSG = 'Use the new lambda literal syntax ' \
'`->(params) {...}`.'.freeze
SINGLE_NO_ARG_MSG = 'Use the new lambda literal syntax ' \
'`-> {...}`.'.freeze
MULTI_MSG = 'Use the `lambda` method for multi-line lambdas.'.freeze
@@ -24,11 +22,11 @@
# (send nil :lambda)
# ...)
block_method, args, = *node
return unless block_method == TARGET
- selector = block_method.loc.selector.source
+ selector = block_method.source
length = lambda_length(node)
if selector != '->' && length == 1
add_offense_for_single_line(node, block_method.source_range, args)
elsif selector == '->' && length > 1
@@ -51,14 +49,18 @@
end_line = block_node.loc.end.line
end_line - start_line + 1
end
- def correction(node)
- lambda do |corrector|
- block_method, _args = *node
+ def autocorrect(node)
+ block_method, _args = *node
+ selector = block_method.source
+ # Don't autocorrect if this would change the meaning of the code
+ return if selector == '->' && arg_to_unparenthesized_call?(node)
+
+ lambda do |corrector|
if block_method.source == 'lambda'
autocorrect_old_to_new(corrector, node)
else
autocorrect_new_to_old(corrector, node)
end
@@ -99,9 +101,18 @@
(block_begin == selector_end)
end
def lambda_arg_string(args)
args.children.map(&:source).join(', ')
+ end
+
+ def arg_to_unparenthesized_call?(node)
+ parent = node.parent
+ return false unless parent && parent.send_type?
+ return false if parenthesized_call?(parent)
+
+ index = parent.children.index { |c| c.equal?(node) }
+ index >= 2
end
end
end
end
end