Sha256: 3b4da9fc86b38c0c7ab4fad34f2830fa78868281252342331cf7f6d57b05b7f7

Contents?: true

Size: 1.6 KB

Versions: 5

Compression:

Stored size: 1.6 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for the presence of `method_missing` without also
      # defining `respond_to_missing?` and falling back on `super`.
      #
      # @example
      #   #bad
      #   def method_missing(name, *args)
      #     # ...
      #   end
      #
      #   #good
      #   def respond_to_missing?(name, include_private)
      #     # ...
      #   end
      #
      #   def method_missing(name, *args)
      #     # ...
      #     super
      #   end
      class MethodMissing < Cop
        MSG = 'When using `method_missing`, %<instructions>s.'.freeze

        def on_def(node)
          return unless node.method?(:method_missing)

          check(node)
        end
        alias on_defs on_def

        private

        def check(node)
          return if calls_super?(node) && implements_respond_to_missing?(node)

          add_offense(node)
        end

        def message(node)
          instructions = []

          unless implements_respond_to_missing?(node)
            instructions << 'define `respond_to_missing?`'.freeze
          end

          unless calls_super?(node)
            instructions << 'fall back on `super`'.freeze
          end

          format(MSG, instructions: instructions.join(' and '))
        end

        def calls_super?(node)
          node.descendants.any?(&:zsuper_type?)
        end

        def implements_respond_to_missing?(node)
          node.parent.each_child_node(node.type).any? do |sibling|
            sibling.method?(:respond_to_missing?)
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rubocop-0.55.0 lib/rubocop/cop/style/method_missing.rb
rubocop-0.54.0 lib/rubocop/cop/style/method_missing.rb
rubocop-0.53.0 lib/rubocop/cop/style/method_missing.rb
rubocop-0.52.1 lib/rubocop/cop/style/method_missing.rb
rubocop-0.52.0 lib/rubocop/cop/style/method_missing.rb