forked from rubocop/rubocop
/
space_before_first_arg.rb
67 lines (56 loc) · 1.98 KB
/
space_before_first_arg.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
# frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that exactly one space is used between a method name and the
# first argument for method calls without parentheses.
#
# Alternatively, extra spaces can be added to align the argument with
# something on a preceding or following line, if the AllowForAlignment
# config parameter is true.
#
# @example
# # bad
# something x
# something y, z
# something'hello'
#
# # good
# something x
# something y, z
# something 'hello'
#
class SpaceBeforeFirstArg < Cop
include PrecedingFollowingAlignment
include RangeHelp
MSG = 'Put one space between the method name and ' \
'the first argument.'.freeze
def on_send(node)
return unless regular_method_call_with_arguments?(node)
return unless expect_params_after_method_name?(node)
first_arg = node.first_argument.source_range
first_arg_with_space = range_with_surrounding_space(range: first_arg,
side: :left)
space = range_between(first_arg_with_space.begin_pos,
first_arg.begin_pos)
add_offense(space, location: space) if space.length != 1
end
alias on_csend on_send
def autocorrect(range)
->(corrector) { corrector.replace(range, ' ') }
end
private
def regular_method_call_with_arguments?(node)
node.arguments? && !node.operator_method? && !node.setter_method?
end
def expect_params_after_method_name?(node)
return false if node.parenthesized?
first_arg = node.first_argument
same_line?(first_arg, node) &&
!(allow_for_alignment? &&
aligned_with_something?(first_arg.source_range))
end
end
end
end
end