class RuboCop::Cop::Style::RedundantReturn
This cop checks for redundant `return` expressions.
@example
def test return something end def test one two three return something end
It should be extended to handle methods whose body is if/else or a case expression with a default branch.
Constants
- MSG
Private Instance Methods
add_braces(corrector, node)
click to toggle source
# File lib/rubocop/cop/style/redundant_return.rb, line 58 def add_braces(corrector, node) kids = node.children.map(&:source_range) corrector.insert_before(kids.first, '{') corrector.insert_after(kids.last, '}') end
add_brackets(corrector, node)
click to toggle source
# File lib/rubocop/cop/style/redundant_return.rb, line 52 def add_brackets(corrector, node) kids = node.children.map(&:source_range) corrector.insert_before(kids.first, '[') corrector.insert_after(kids.last, ']') end
arguments?(args)
click to toggle source
# File lib/rubocop/cop/style/redundant_return.rb, line 64 def arguments?(args) return false if args.empty? return true if args.size > 1 !args.first.begin_type? || !args.first.children.empty? end
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/style/redundant_return.rb, line 30 def autocorrect(node) lambda do |corrector| unless arguments?(node.children) corrector.replace(node.source_range, 'nil') next end return_value, = *node if node.children.size > 1 add_brackets(corrector, node) elsif return_value.hash_type? add_braces(corrector, return_value) unless braces?(return_value) end return_kw = range_with_surrounding_space(node.loc.keyword, :right) corrector.remove(return_kw) end end
braces?(arg)
click to toggle source
# File lib/rubocop/cop/style/redundant_return.rb, line 48 def braces?(arg) arg.loc.begin end
check_return_node(node)
click to toggle source
# File lib/rubocop/cop/style/redundant_return.rb, line 86 def check_return_node(node) return if cop_config['AllowMultipleReturnValues'] && node.children.size > 1 add_offense(node, :keyword) end
on_method_def(_node, _method_name, _args, body)
click to toggle source
# File lib/rubocop/cop/style/redundant_return.rb, line 71 def on_method_def(_node, _method_name, _args, body) return unless body if body.type == :return check_return_node(body) elsif body.type == :begin expressions = *body last_expr = expressions.last if last_expr && last_expr.type == :return check_return_node(last_expr) end end end