123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::CaseLikeIf

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/case_like_if.rb

Overview

Identifies places where if-elsif constructions can be replaced with case-when.

Examples:

MinBranchesCount: 3 (default)

# bad
if status == :active
  perform_action
elsif status == :inactive || status == :hibernating
  check_timeout
elsif status == :invalid
  report_invalid
else
  final_action
end

# good
case status
when :active
  perform_action
when :inactive, :hibernating
  check_timeout
when :invalid
  report_invalid
else
  final_action
end

MinBranchesCount: 4

# good
if status == :active
  perform_action
elsif status == :inactive || status == :hibernating
  check_timeout
elsif status == :invalid
  report_invalid
else
  final_action
end

Cop Safety Information:

  • This cop is unsafe. case statements use === for equality, so if the original conditional used a different equality operator, the behavior may be different.

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

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.

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

Returns a url to view this cops documentation online.

.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::MinBranchesCount - 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::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_gem_version

Returns a gems locked versions (i.e.

#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

Actually private methods.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

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

Instance Method Details

#autocorrect(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 81

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

  corrector.insert_before(node, "case #{target.source}\n#{indent(node)}")

  branch_conditions(node).each do |branch_condition|
    conditions = []
    collect_conditions(branch_condition, target, conditions)

    range = correction_range(branch_condition)
    branch_replacement = "when #{conditions.map(&:source).join(', ')}"
    corrector.replace(range, branch_replacement)
  end
end

#branch_conditions(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 228

def branch_conditions(node)
  conditions = []
  while node&.if_type? && !node.ternary?
    conditions << node.condition
    node = node.else_branch
  end
  conditions
end

#class_reference?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 246

def class_reference?(node)
  node.const_type? && node.children[1].match?(/[[:lower:]]/)
end

#collect_conditions(node, target, conditions) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 166

def collect_conditions(node, target, conditions)
  condition =
    case node.type
    when :begin
      return collect_conditions(node.children.first, target, conditions)
    when :or
      return collect_conditions(node.lhs, target, conditions) &&
             collect_conditions(node.rhs, target, conditions)
    when :match_with_lvasgn
      lhs, rhs = *node # rubocop:disable InternalAffairs/NodeDestructuring
      condition_from_binary_op(lhs, rhs, target)
    when :send
      condition_from_send_node(node, target)
    end

  conditions << condition if condition
end

#condition_from_binary_op(lhs, rhs, target) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 217

def condition_from_binary_op(lhs, rhs, target)
  lhs = deparenthesize(lhs)
  rhs = deparenthesize(rhs)

  if lhs == target
    rhs
  elsif rhs == target
    lhs
  end
end

#condition_from_equality_node(node, target) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 201

def condition_from_equality_node(node, target)
  condition = condition_from_binary_op(node.receiver, node.first_argument, target)
  condition if condition && !class_reference?(condition)
end

#condition_from_include_or_cover_node(node, target) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 210

def condition_from_include_or_cover_node(node, target)
  return unless (receiver = node.receiver)

  receiver = deparenthesize(receiver)
  receiver if receiver.range_type? && node.first_argument == target
end

#condition_from_match_node(node, target) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 206

def condition_from_match_node(node, target)
  condition_from_binary_op(node.receiver, node.first_argument, target)
end

#condition_from_send_node(node, target) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 185

def condition_from_send_node(node, target)
  case node.method_name
  when :is_a?
    node.first_argument if node.receiver == target
  when :==, :eql?, :equal?
    condition_from_equality_node(node, target)
  when :=~, :match, :match?
    condition_from_match_node(node, target)
  when :===
    node.receiver if node.first_argument == target
  when :include?, :cover?
    condition_from_include_or_cover_node(node, target)
  end
end

#const_reference?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 237

def const_reference?(node)
  return false unless node.const_type?

  name = node.children[1].to_s

  # We can no be sure if, e.g. `C`, represents a constant or a class reference
  name.length > 1 && name == name.upcase
end

#correction_range(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 255

def correction_range(node)
  range_between(node.parent.loc.keyword.begin_pos, node.source_range.end_pos)
end

#deparenthesize(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 250

def deparenthesize(node)
  node = node.children.last while node.begin_type?
  node
end

#find_target(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 102

def find_target(node)
  case node.type
  when :begin
    find_target(node.children.first)
  when :or
    find_target(node.lhs)
  when :match_with_lvasgn
    lhs, rhs = *node # rubocop:disable InternalAffairs/NodeDestructuring
    if lhs.regexp_type?
      rhs
    elsif rhs.regexp_type?
      lhs
    end
  when :send
    find_target_in_send_node(node)
  end
end

#find_target_in_equality_node(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 136

def find_target_in_equality_node(node)
  argument = node.first_argument
  receiver = node.receiver
  return unless argument && receiver

  if argument.literal? || const_reference?(argument)
    receiver
  elsif receiver.literal? || const_reference?(receiver)
    argument
  end
end

#find_target_in_include_or_cover_node(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 148

def find_target_in_include_or_cover_node(node)
  return unless (receiver = node.receiver)

  node.first_argument if deparenthesize(receiver).range_type?
end

#find_target_in_match_node(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 154

def find_target_in_match_node(node)
  argument = node.first_argument
  receiver = node.receiver
  return unless receiver

  if receiver.regexp_type?
    argument
  elsif argument.regexp_type?
    receiver
  end
end

#find_target_in_send_node(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 121

def find_target_in_send_node(node)
  case node.method_name
  when :is_a?
    node.receiver
  when :==, :eql?, :equal?
    find_target_in_equality_node(node)
  when :===
    node.first_argument
  when :include?, :cover?
    find_target_in_include_or_cover_node(node)
  when :match, :match?, :=~
    find_target_in_match_node(node)
  end
end

#on_if(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 57

def on_if(node)
  return unless should_check?(node)

  target = find_target(node.condition)
  return unless target

  conditions = []
  convertible = true

  branch_conditions(node).each do |branch_condition|
    return false if regexp_with_working_captures?(branch_condition)

    conditions << []
    convertible = collect_conditions(branch_condition, target, conditions.last)
    break unless convertible
  end

  return unless convertible

  add_offense(node) { |corrector| autocorrect(corrector, node) }
end

#regexp_with_named_captures?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 271

def regexp_with_named_captures?(node)
  node.regexp_type? && node.each_capture(named: true).count.positive?
end

#regexp_with_working_captures?(node) ⇒ Boolean (private)

Named captures work with =~ (if regexp is on lhs) and with match (both sides)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 260

def regexp_with_working_captures?(node)
  case node.type
  when :match_with_lvasgn
    lhs, _rhs = *node # rubocop:disable InternalAffairs/NodeDestructuring
    node.loc.selector.source == '=~' && regexp_with_named_captures?(lhs)
  when :send
    node.method?(:match) &&
      [node.receiver, node.first_argument].any? { |n| regexp_with_named_captures?(n) }
  end
end

#should_check?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/case_like_if.rb', line 96

def should_check?(node)
  !node.unless? && !node.elsif? && !node.modifier_form? && !node.ternary? &&
    node.elsif_conditional? && min_branches_count?(node)
end