Sha256: 51a4e91679e8c4e87e82b152305f1a876e1548473c00e38d75e0b6ef8d209328

Contents?: true

Size: 1.29 KB

Versions: 13

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for uses of rescue in its modifier form.
      class RescueModifier < Cop
        include AutocorrectAlignment

        MSG = 'Avoid using `rescue` in its modifier form.'.freeze

        def investigate(processed_source)
          @modifier_locations = processed_source
                                .tokens
                                .select { |t| t.type == :kRESCUE_MOD }
                                .map(&:pos)
        end

        def on_resbody(node)
          return unless modifier?(node)
          add_offense(node.parent, :expression)
        end

        def autocorrect(node)
          operation, rescue_modifier, = *node
          *_, rescue_args = *rescue_modifier

          indent = indentation(node)
          correction =
            "begin\n" \
            "#{operation.source.gsub(/^/, indent)}" \
            "\n#{offset(node)}rescue\n" \
            "#{rescue_args.source.gsub(/^/, indent)}" \
            "\n#{offset(node)}end"

          lambda do |corrector|
            corrector.replace(node.source_range, correction)
          end
        end

        private

        def modifier?(node)
          @modifier_locations.include?(node.loc.keyword)
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/rescue_modifier.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/rescue_modifier.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/rescue_modifier.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/rescue_modifier.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/rescue_modifier.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/rescue_modifier.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/rescue_modifier.rb
rubocop-0.47.1 lib/rubocop/cop/style/rescue_modifier.rb
rubocop-0.47.0 lib/rubocop/cop/style/rescue_modifier.rb
rubocop-0.46.0 lib/rubocop/cop/style/rescue_modifier.rb
rubocop-0.45.0 lib/rubocop/cop/style/rescue_modifier.rb
rubocop-0.44.1 lib/rubocop/cop/style/rescue_modifier.rb
rubocop-0.44.0 lib/rubocop/cop/style/rescue_modifier.rb