lib/rubocop/cop/style/ternary_parentheses.rb in rubocop-0.89.1 vs lib/rubocop/cop/style/ternary_parentheses.rb in rubocop-0.90.0

- old
+ new

@@ -52,14 +52,15 @@ # # @example AllowSafeAssignment: false # # bad # foo = (bar = baz) ? a : b # - class TernaryParentheses < Cop + class TernaryParentheses < Base include SafeAssignment include ConfigurableEnforcedStyle include SurroundingSpace + extend AutoCorrector VARIABLE_TYPES = AST::Node::VARIABLES NON_COMPLEX_TYPES = [*VARIABLE_TYPES, :const, :defined?, :yield].freeze MSG = '%<command>s parentheses for ternary conditions.' @@ -68,33 +69,37 @@ 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) + message = message(node) + + add_offense(node.source_range, message: message) do |corrector| + autocorrect(corrector, node) + end end def only_closing_parenthesis_is_last_line?(condition) condition.source.split("\n").last == ')' end - def autocorrect(node) + private + + def autocorrect(corrector, node) condition = node.condition return nil if parenthesized?(condition) && (safe_assignment?(condition) || unsafe_autocorrect?(condition)) if parenthesized?(condition) - correct_parenthesized(condition) + correct_parenthesized(corrector, condition) else - correct_unparenthesized(condition) + correct_unparenthesized(corrector, condition) end end - private - def offense?(node) condition = node.condition if safe_assignment?(condition) !safe_assignment_allowed? @@ -189,25 +194,21 @@ def_node_matcher :method_name, <<~PATTERN {($:defined? (send nil? _) ...) (send {_ nil?} $_ _ ...)} PATTERN - def correct_parenthesized(condition) - lambda do |corrector| - corrector.remove(condition.loc.begin) - corrector.remove(condition.loc.end) + def correct_parenthesized(corrector, condition) + corrector.remove(condition.loc.begin) + corrector.remove(condition.loc.end) - # Ruby allows no space between the question mark and parentheses. - # If we remove the parentheses, we need to add a space or we'll - # generate invalid code. - corrector.insert_after(condition.loc.end, ' ') unless whitespace_after?(condition) - end + # Ruby allows no space between the question mark and parentheses. + # If we remove the parentheses, we need to add a space or we'll + # generate invalid code. + corrector.insert_after(condition.loc.end, ' ') unless whitespace_after?(condition) end - def correct_unparenthesized(condition) - lambda do |corrector| - corrector.wrap(condition, '(', ')') - end + def correct_unparenthesized(corrector, condition) + corrector.wrap(condition, '(', ')') end def whitespace_after?(node) index = index_of_last_token(node) last_token = processed_source.tokens[index]