Class: RuboCop::Cop::Tablecop::CondenseWhen

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/tablecop/condense_when.rb

Overview

Checks for multi-line ‘when` clauses that could be condensed to a single line using the `then` keyword, and aligns `then` keywords across siblings.

This cop encourages a table-like, vertically-aligned style for case statements where each when clause fits on one line.

Examples:

# bad
case foo
when 1
  "one"
when 200
  "two hundred"
end

# good (aligned)
case foo
when 1   then "one"
when 200 then "two hundred"
end

# also good (body too complex for single line)
case foo
when 1
  do_something
  do_something_else
end

Constant Summary collapse

MSG =
"Condense `when` to single line with aligned `then`"

Instance Method Summary collapse

Instance Method Details

#on_case(node) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/tablecop/condense_when.rb', line 39

def on_case(node)
  when_nodes = node.when_branches
  return if when_nodes.empty?

  # Analyze which whens can be condensed
  condensable = when_nodes.map { |w| [w, condensable?(w)] }

  # If none can be condensed, nothing to do
  return unless condensable.any? { |_, can| can }

  # Calculate alignment width from all condensable whens
  max_condition_width = calculate_max_condition_width(condensable)

  # Check if alignment would exceed line length for any condensable when
  use_alignment = can_align_all?(condensable, max_condition_width, node)

  # Register offenses and corrections for each condensable when
  condensable.each do |when_node, can_condense|
    next unless can_condense
    next if when_node.single_line?  # Already condensed

    register_offense(when_node, max_condition_width, use_alignment, node)
  end
end