Sha256: 9edf991142beeeab3ce4273a7d7f18fbeafc7c9d5cb7ecd4e99e48d776d4d3c3

Contents?: true

Size: 1.52 KB

Versions: 6

Compression:

Stored size: 1.52 KB

Contents

# encoding: utf-8
# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # This cop looks for error classes inheriting from `Exception`.
      # It is configurable to suggest using either `RuntimeError` (default) or
      # `StandardError` instead.
      #
      # @example
      #
      #   # bad
      #
      #   class C < Exception; end
      #
      # @example
      #
      #   # EnforcedStyle: runtime_error (default)
      #
      #   # good
      #
      #   class C < RuntimeError; end
      #
      # @example
      #
      #   # EnforcedStyle: standard_error
      #
      #   # good
      #
      #   class C < StandardError; end
      class InheritException < Cop
        include ConfigurableEnforcedStyle

        MSG = 'Inherit from `%s` instead of `Exception`.'.freeze
        PREFERRED_BASE_CLASS = {
          runtime_error: 'RuntimeError',
          standard_error: 'StandardError'
        }.freeze

        def on_class(node)
          _class, base_class, _body = *node

          return if base_class.nil?

          check(base_class)
        end

        private

        def check(node)
          if node.const_name == 'Exception'
            add_offense(node, :expression, format(MSG, preferred_base_class))
          end
        end

        def autocorrect(node)
          lambda do |corrector|
            corrector.replace(node.loc.expression, preferred_base_class)
          end
        end

        def preferred_base_class
          PREFERRED_BASE_CLASS[style]
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
fluent-plugin-detect-memb-exceptions-0.0.2 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/lint/inherit_exception.rb
fluent-plugin-detect-memb-exceptions-0.0.1 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/lint/inherit_exception.rb
rubocop-0.42.0 lib/rubocop/cop/lint/inherit_exception.rb
rubocop-0.41.2 lib/rubocop/cop/lint/inherit_exception.rb
rubocop-0.41.1 lib/rubocop/cop/lint/inherit_exception.rb
rubocop-0.41.0 lib/rubocop/cop/lint/inherit_exception.rb