forked from rubocop/rubocop
/
optional_arguments.rb
58 lines (49 loc) · 1.51 KB
/
optional_arguments.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
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for optional arguments to methods
# that do not come at the end of the argument list.
#
# @example
# # bad
# def foo(a = 1, b, c)
# end
#
# # good
# def baz(a, b, c = 1)
# end
#
# def foobar(a = 1, b = 2, c = 3)
# end
class OptionalArguments < Cop
MSG = 'Optional arguments should appear at the end ' \
'of the argument list.'
def on_def(node)
each_misplaced_optional_arg(node.arguments) do |argument|
add_offense(argument)
end
end
private
def each_misplaced_optional_arg(arguments)
optarg_positions, arg_positions = argument_positions(arguments)
return if optarg_positions.empty? || arg_positions.empty?
optarg_positions.each do |optarg_position|
# there can only be one group of optional arguments
break if optarg_position > arg_positions.max
yield arguments[optarg_position]
end
end
def argument_positions(arguments)
optarg_positions = []
arg_positions = []
arguments.each_with_index do |argument, index|
optarg_positions << index if argument.optarg_type?
arg_positions << index if argument.arg_type?
end
[optarg_positions, arg_positions]
end
end
end
end
end