class RuboCop::Cop::Lint::DuplicateBranch
end
else MEDIUM_SIZE
when “large” then LARGE_SIZE
when “medium” then MEDIUM_SIZE
when “small” then SMALL_SIZE
case size
# good
@example IgnoreConstantBranches: true
end
else 250
when “large” then 1000
when “medium” then 250
when “small” then 100
case size
# good
@example IgnoreLiteralBranches: true
end
handle_error
rescue FooError, BarError
do_something
begin
# good
end
handle_error
rescue BarError
handle_error
rescue FooError
do_something
begin
# bad
end
do_something_else
else
do_foo
when foo, bar
case x
# good
end
do_something_else
else
do_foo
when bar
do_foo
when foo
case x
# bad
end
do_something_else
do_foo
if foo || bar
# good
end
do_something_else
do_foo
elsif bar
do_something_else
do_foo
if foo
# bad
@example
as offenses if they return a constant value.
With ‘IgnoreConstantBranches: true`, branches are not registered
the above basic literal values.
return an array, hash, regexp or range that only contains one of
integer, float, rational, complex, `true`, `false`, or `nil`), or
as offenses if they return a basic literal value (string, symbol,
With `IgnoreLiteralBranches: true`, branches are not registered
within `if/unless`, `case-when`, `case-in` and `rescue` constructs.
Checks that there are no repeated bodies
def branches(node)
def branches(node) node.branches.compact end
def consider_branch?(branch)
def consider_branch?(branch) return false if ignore_literal_branches? && literal_branch?(branch) return false if ignore_constant_branches? && const_branch?(branch) true end
def const_branch?(branch)
def const_branch?(branch) branch.const_type? end
def ignore_constant_branches?
def ignore_constant_branches? cop_config.fetch('IgnoreConstantBranches', false) end
def ignore_literal_branches?
def ignore_literal_branches? cop_config.fetch('IgnoreLiteralBranches', false) end
def literal_branch?(branch) # rubocop:disable Metrics/CyclomaticComplexity
def literal_branch?(branch) # rubocop:disable Metrics/CyclomaticComplexity return false if !branch.literal? || branch.xstr_type? return true if branch.basic_literal? branch.each_descendant.all? do |node| node.basic_literal? || node.pair_type? || # hash keys and values are contained within a `pair` node (node.const_type? && ignore_constant_branches?) end end
def offense_range(duplicate_branch)
def offense_range(duplicate_branch) parent = duplicate_branch.parent if parent.respond_to?(:else_branch) && parent.else_branch.equal?(duplicate_branch) if parent.if_type? && parent.ternary? duplicate_branch.source_range else parent.loc.else end else parent.source_range end end
def on_branching_statement(node)
def on_branching_statement(node) branches(node).each_with_object(Set.new) do |branch, previous| next unless consider_branch?(branch) add_offense(offense_range(branch)) unless previous.add?(branch) end end