Sha256: e289f40746221f0eff5d3b17b47ed5af2f925a8c236573869c97e3b7182652c1

Contents?: true

Size: 1.63 KB

Versions: 10

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for redundant `begin` blocks.
      #
      # Currently it checks for code like this:
      #
      # @example
      #
      #   # bad
      #   def redundant
      #     begin
      #       ala
      #       bala
      #     rescue StandardError => e
      #       something
      #     end
      #   end
      #
      #   # good
      #   def preferred
      #     ala
      #     bala
      #   rescue StandardError => e
      #     something
      #   end
      #
      #   # bad
      #   # When using Ruby 2.5 or later.
      #   do_something do
      #     begin
      #       something
      #     rescue => ex
      #       anything
      #     end
      #   end
      #
      #   # good
      #   # In Ruby 2.5 or later, you can omit `begin` in `do-end` block.
      #   do_something do
      #     something
      #   rescue => ex
      #     anything
      #   end
      class RedundantBegin < Cop
        MSG = 'Redundant `begin` block detected.'.freeze

        def on_def(node)
          check(node)
        end
        alias on_defs on_def

        def on_block(node)
          return if target_ruby_version < 2.5
          return if node.braces?
          check(node)
        end

        def autocorrect(node)
          lambda do |corrector|
            corrector.remove(node.loc.begin)
            corrector.remove(node.loc.end)
          end
        end

        private

        def check(node)
          return unless node.body && node.body.kwbegin_type?

          add_offense(node.body, location: :begin)
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 2 rubygems

Version Path
rubocop-0.58.2 lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.58.1 lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.58.0 lib/rubocop/cop/style/redundant_begin.rb
vagrant-packet-0.1.1 vendor/bundle/ruby/2.4.0/gems/rubocop-0.57.2/lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.57.2 lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.57.1 lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.57.0 lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.56.0 lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.55.0 lib/rubocop/cop/style/redundant_begin.rb
rubocop-0.54.0 lib/rubocop/cop/style/redundant_begin.rb