Sha256: e2165bd14e29cbe725b9e9a84babbaaacb1530a27b4c15ea0ba544a8d9172404

Contents?: true

Size: 1.86 KB

Versions: 4

Compression:

Stored size: 1.86 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for RuntimeError as the argument of raise/fail.
      #
      # It checks for code like this:
      #
      # @example
      #   # Bad
      #   raise RuntimeError, 'message'
      #
      #   # Bad
      #   raise RuntimeError.new('message')
      #
      #   # Good
      #   raise 'message'
      class RedundantException < Base
        extend AutoCorrector

        MSG_1 = 'Redundant `RuntimeError` argument can be removed.'
        MSG_2 = 'Redundant `RuntimeError.new` call can be replaced with ' \
                'just the message.'

        # Switch `raise RuntimeError, 'message'` to `raise 'message'`, and
        # `raise RuntimeError.new('message')` to `raise 'message'`.
        def on_send(node)
          fix_exploded(node) || fix_compact(node)
        end

        def fix_exploded(node)
          exploded?(node) do |command, message|
            add_offense(node, message: MSG_1) do |corrector|
              if node.parenthesized?
                corrector.replace(node,
                                  "#{command}(#{message.source})")
              else
                corrector.replace(node,
                                  "#{command} #{message.source}")
              end
            end
          end
        end

        def fix_compact(node)
          compact?(node) do |new_call, message|
            add_offense(node, message: MSG_2) do |corrector|
              corrector.replace(new_call, message.source)
            end
          end
        end

        def_node_matcher :exploded?, <<~PATTERN
          (send nil? ${:raise :fail} (const {nil? cbase} :RuntimeError) $_)
        PATTERN

        def_node_matcher :compact?, <<~PATTERN
          (send nil? {:raise :fail} $(send (const {nil? cbase} :RuntimeError) :new $_))
        PATTERN
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
rubocop-0.88.0 lib/rubocop/cop/style/redundant_exception.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/redundant_exception.rb
rubocop-0.87.1 lib/rubocop/cop/style/redundant_exception.rb
rubocop-0.87.0 lib/rubocop/cop/style/redundant_exception.rb