lib/rubocop/cop/style/ternary_parentheses.rb in rubocop-0.74.0 vs lib/rubocop/cop/style/ternary_parentheses.rb in rubocop-0.75.0
- old
+ new
@@ -6,10 +6,15 @@
# This cop checks for the presence of parentheses around ternary
# conditions. It is configurable to enforce inclusion or omission of
# parentheses using `EnforcedStyle`. Omission is only enforced when
# removing the parentheses won't cause a different behavior.
#
+ # `AllowSafeAssignment` option for safe assignment.
+ # By safe assignment we mean putting parentheses around
+ # an assignment to indicate "I know I'm using an assignment
+ # as a condition. It's not a mistake."
+ #
# @example EnforcedStyle: require_no_parentheses (default)
# # bad
# foo = (bar?) ? a : b
# foo = (bar.baz?) ? a : b
# foo = (bar && baz) ? a : b
@@ -38,10 +43,19 @@
#
# # good
# foo = bar? ? a : b
# foo = bar.baz? ? a : b
# foo = (bar && baz) ? a : b
+ #
+ # @example AllowSafeAssignment: true (default)
+ # # good
+ # foo = (bar = baz) ? a : b
+ #
+ # @example AllowSafeAssignment: false
+ # # bad
+ # foo = (bar = baz) ? a : b
+ #
class TernaryParentheses < Cop
include SafeAssignment
include ConfigurableEnforcedStyle
include SurroundingSpace
@@ -51,12 +65,17 @@
MSG = '%<command>s parentheses for ternary conditions.'
MSG_COMPLEX = '%<command>s parentheses for ternary expressions with' \
' complex conditions.'
def on_if(node)
+ return if only_closing_parenthesis_is_last_line?(node.condition)
return unless node.ternary? && !infinite_loop? && offense?(node)
add_offense(node, location: node.source_range)
+ end
+
+ def only_closing_parenthesis_is_last_line?(condition)
+ condition.source.split("\n").last == ')'
end
def autocorrect(node)
condition = node.condition