123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::TernaryParentheses

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/ternary_parentheses.rb

Overview

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."

Examples:

EnforcedStyle: require_no_parentheses (default)

# bad
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = (bar && baz) ? a : b

# good
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = bar && baz ? a : b

EnforcedStyle: require_parentheses

# bad
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = bar && baz ? a : b

# good
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = (bar && baz) ? a : b

EnforcedStyle: require_parentheses_when_complex

# bad
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = bar && baz ? a : b

# good
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = (bar && baz) ? a : b

AllowSafeAssignment: true (default)

# good
foo = (bar = baz) ? a : b

AllowSafeAssignment: false

# bad
foo = (bar = baz) ? a : b

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

SYMBOL_TO_STRING_CACHE

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

::RuboCop::Cop::SurroundingSpace - Included

NO_SPACE_COMMAND, SINGLE_SPACE_REGEXP, SPACE_COMMAND

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

.builtin?

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Cops (other than builtin) are encouraged to implement this.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::SurroundingSpace - Included

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

::RuboCop::Cop::SafeAssignment - Included

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?, #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range, #reset_investigation, #use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Attribute Details

#require_parentheses?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 161

def require_parentheses?
  style == :require_parentheses
end

#require_parentheses_when_complex?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 165

def require_parentheses_when_complex?
  style == :require_parentheses_when_complex
end

Instance Method Details

#autocorrect(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 100

def autocorrect(corrector, node)
  condition = node.condition

  return nil if parenthesized?(condition) &&
                (safe_assignment?(condition) || unsafe_autocorrect?(condition))

  if parenthesized?(condition)
    correct_parenthesized(corrector, condition)
  else
    correct_unparenthesized(corrector, condition)
  end
end

#below_ternary_precedence?(child) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 183

def below_ternary_precedence?(child)
  # Handle English "or", e.g. 'foo or bar ? a : b'
  (child.or_type? && child.semantic_operator?) ||
    # Handle English "and", e.g. 'foo and bar ? a : b'
    (child.and_type? && child.semantic_operator?) ||
    # Handle English "not", e.g. 'not foo ? a : b'
    (child.send_type? && child.prefix_not?)
end

#complex_condition?(condition) ⇒ Boolean (private)

If the condition is parenthesized we recurse and check for any complex expressions within it.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 131

def complex_condition?(condition)
  if condition.begin_type?
    condition.to_a.any? { |x| complex_condition?(x) }
  else
    !non_complex_expression?(condition)
  end
end

#condition_as_parenthesized_one_line_pattern_matching?(condition) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 89

def condition_as_parenthesized_one_line_pattern_matching?(condition)
  return false unless condition.parenthesized_call?
  return false unless (first_child = condition.children.first)

  if target_ruby_version >= 3.0
    first_child.match_pattern_p_type?
  else
    first_child.match_pattern_type? # For Ruby 2.7's one line pattern matching AST.
  end
end

#correct_parenthesized(corrector, condition) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 198

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

#correct_unparenthesized(corrector, condition) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 208

def correct_unparenthesized(corrector, condition)
  corrector.wrap(condition, '(', ')')
end

#message(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 151

def message(node)
  if require_parentheses_when_complex?
    command = parenthesized?(node.condition) ? 'Only use' : 'Use'
    format(MSG_COMPLEX, command: command)
  else
    command = require_parentheses? ? 'Use' : 'Omit'
    format(MSG, command: command)
  end
end

#method_name(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 193

def_node_matcher :method_name, <<~PATTERN
  {($:defined? _ ...)
   (send {_ nil?} $_ _ ...)}
PATTERN

#non_complex_expression?(condition) ⇒ Boolean (private)

Anything that is not a variable, constant, or method/.method call will be counted as a complex expression.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 141

def non_complex_expression?(condition)
  NON_COMPLEX_TYPES.include?(condition.type) || non_complex_send?(condition)
end

#non_complex_send?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 145

def non_complex_send?(node)
  return false unless node.call_type?

  !node.operator_method? || node.method?(:[])
end

#offense?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 113

def offense?(node)
  condition = node.condition

  if safe_assignment?(condition)
    !safe_assignment_allowed?
  else
    parens = parenthesized?(condition)
    case style
    when :require_parentheses_when_complex
      complex_condition?(condition) ? !parens : parens
    else
      require_parentheses? ? !parens : parens
    end
  end
end

#on_if(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 69

def on_if(node)
  condition = node.condition

  return if only_closing_parenthesis_is_last_line?(condition)
  return if condition_as_parenthesized_one_line_pattern_matching?(condition)
  return unless node.ternary? && offense?(node)

  message = message(node)

  add_offense(node.source_range, message: message) do |corrector|
    autocorrect(corrector, node)
  end
end

#only_closing_parenthesis_is_last_line?(condition) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 85

def only_closing_parenthesis_is_last_line?(condition)
  condition.source.split("\n").last == ')'
end

#parenthesized?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 169

def parenthesized?(node)
  node.begin_type?
end

#unparenthesized_method_call?(child) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 179

def unparenthesized_method_call?(child)
  /^[a-z]/i.match?(method_name(child)) && !child.parenthesized?
end

#unsafe_autocorrect?(condition) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 173

def unsafe_autocorrect?(condition)
  condition.children.any? do |child|
    unparenthesized_method_call?(child) || below_ternary_precedence?(child)
  end
end

#whitespace_after?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 212

def whitespace_after?(node)
  last_token = processed_source.last_token_of(node)
  last_token.space_after?
end