/
multiline_ternary_operator.rb
60 lines (53 loc) · 1.49 KB
/
multiline_ternary_operator.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
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for multi-line ternary op expressions.
#
# NOTE: `return if ... else ... end` is syntax error. If `return` is used before
# multiline ternary operator expression, it cannot be auto-corrected.
#
# @example
# # bad
# a = cond ?
# b : c
# a = cond ? b :
# c
# a = cond ?
# b :
# c
#
# # good
# a = cond ? b : c
# a = if cond
# b
# else
# c
# end
class MultilineTernaryOperator < Base
extend AutoCorrector
MSG = 'Avoid multi-line ternary operators, ' \
'use `if` or `unless` instead.'
def on_if(node)
return unless offense?(node)
add_offense(node) do |corrector|
# `return if ... else ... end` is syntax error. If `return` is used before
# multiline ternary operator expression, it cannot be auto-corrected.
next unless offense?(node) && !node.parent.return_type?
corrector.replace(node, <<~RUBY.chop)
if #{node.condition.source}
#{node.if_branch.source}
else
#{node.else_branch.source}
end
RUBY
end
end
private
def offense?(node)
node.ternary? && node.multiline?
end
end
end
end
end