/
space_in_lambda_literal.rb
82 lines (71 loc) · 2.39 KB
/
space_in_lambda_literal.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
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
74
75
76
77
78
79
80
81
82
# frozen_string_literal: true
module RuboCop
module Cop
module Layout
# This cop checks for spaces between `->` and opening parameter
# parenthesis (`(`) in lambda literals.
#
# @example EnforcedStyle: require_no_space (default)
# # bad
# a = -> (x, y) { x + y }
#
# # good
# a = ->(x, y) { x + y }
#
# @example EnforcedStyle: require_space
# # bad
# a = ->(x, y) { x + y }
#
# # good
# a = -> (x, y) { x + y }
class SpaceInLambdaLiteral < Cop
include ConfigurableEnforcedStyle
include RangeHelp
MSG_REQUIRE_SPACE = 'Use a space between `->` and ' \
'`(` in lambda literals.'
MSG_REQUIRE_NO_SPACE = 'Do not use spaces between `->` and ' \
'`(` in lambda literals.'
def on_send(node)
return unless arrow_lambda_with_args?(node)
if style == :require_space && !space_after_arrow?(node)
add_offense(node,
location: range_of_offense(node),
message: MSG_REQUIRE_SPACE)
elsif style == :require_no_space && space_after_arrow?(node)
add_offense(node,
location: range_of_offense(node),
message: MSG_REQUIRE_NO_SPACE)
end
end
def autocorrect(lambda_node)
children = lambda_node.parent.children
lambda do |corrector|
if style == :require_space
corrector.insert_before(children[1], ' ')
else
corrector.remove(space_after_arrow(lambda_node))
end
end
end
private
def arrow_lambda_with_args?(node)
node.lambda_literal? && node.parent.arguments?
end
def space_after_arrow?(lambda_node)
!space_after_arrow(lambda_node).empty?
end
def space_after_arrow(lambda_node)
arrow = lambda_node.parent.children[0].source_range
parentheses = lambda_node.parent.children[1].source_range
arrow.end.join(parentheses.begin)
end
def range_of_offense(node)
range_between(
node.parent.loc.expression.begin_pos,
node.parent.arguments.loc.expression.end_pos
)
end
end
end
end
end