Sha256: 2b8863b00c7f43a825e84044de67463fc7b532d2caccd877bd861e11e5d996ed

Contents?: true

Size: 1.49 KB

Versions: 11

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # This cop checks for `return` from an `ensure` block.
      # Explicit return from an ensure block alters the control flow
      # as the return will take precedence over any exception being raised,
      # and the exception will be silently thrown away as if it were rescued.
      #
      # @example
      #
      #   # bad
      #
      #   begin
      #     do_something
      #   ensure
      #     do_something_else
      #     return
      #   end
      #
      # @example
      #
      #   # good
      #
      #   begin
      #     do_something
      #   ensure
      #     do_something_else
      #   end
      class EnsureReturn < Cop
        include RangeHelp

        MSG = 'Do not return from an `ensure` block.'

        def on_ensure(node)
          ensure_body = node.body

          return unless ensure_body

          ensure_body.each_node(:return) do |return_node|
            next if return_node.arguments.size >= 2

            add_offense(return_node, location: :keyword)
          end
        end

        def autocorrect(node)
          lambda do |corrector|
            if node.arguments?
              corrector.replace(node, node.source.gsub(/return\s*/, ''))
            else
              range = range_by_whole_lines(
                node.loc.expression, include_final_newline: true
              )
              corrector.remove(range)
            end
          end
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 3 rubygems

Version Path
rubocop-0.88.0 lib/rubocop/cop/lint/ensure_return.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/lint/ensure_return.rb
rubocop-0.87.1 lib/rubocop/cop/lint/ensure_return.rb
rubocop-0.87.0 lib/rubocop/cop/lint/ensure_return.rb
rubocop-0.86.0 lib/rubocop/cop/lint/ensure_return.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/lint/ensure_return.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/lint/ensure_return.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/lint/ensure_return.rb
rubocop-0.85.1 lib/rubocop/cop/lint/ensure_return.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/lint/ensure_return.rb
rubocop-0.85.0 lib/rubocop/cop/lint/ensure_return.rb