Class: RuboCop::Cop::Style::MixinUsage

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/style/mixin_usage.rb

Overview

Checks that include, extend and prepend statements appear inside classes and modules, not at the top level, so as to not affect the behavior of Object.

Examples:

# bad
include M

class C
end

# bad
extend M

class C
end

# bad
prepend M

class C
end

# good
class C
  include M
end

# good
class C
  extend M
end

# good
class C
  prepend M
end

Constant Summary collapse

MSG =
'`%<statement>s` is used at the top level. Use inside `class` or `module`.'
RESTRICT_ON_SEND =
%i[include extend prepend].freeze

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods inherited from Base

#active_support_extensions_enabled?, #add_global_offense, #add_offense, autocorrect_incompatible_with, badge, #begin_investigation, callbacks_needed, #callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, cop_name, #cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, #inspect, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #ready, #relevant_file?, support_autocorrect?, support_multiple_source?, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#in_top_level_scope?(node) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/rubocop/cop/style/mixin_usage.rb', line 54

def_node_matcher :in_top_level_scope?, <<~PATTERN
  {
    root?                        # either at the top level
    ^[  {kwbegin begin if def}   # or wrapped within one of these
        #in_top_level_scope? ]   # that is in top level scope
  }
PATTERN

#include_statement(node) ⇒ Object



48
49
50
51
# File 'lib/rubocop/cop/style/mixin_usage.rb', line 48

def_node_matcher :include_statement, <<~PATTERN
  (send nil? ${:include :extend :prepend}
    const)
PATTERN

#on_send(node) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/rubocop/cop/style/mixin_usage.rb', line 62

def on_send(node)
  include_statement(node) do |statement|
    return unless in_top_level_scope?(node)

    add_offense(node, message: format(MSG, statement: statement))
  end
end