Class: RuboCop::Cop::Dependency::OverBoundary

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dependency/over_boundary.rb

Overview

Check not to refer constants over dependency boundaries which given from ‘Rules` config.

Examples:

# Rules:
#   - BannedConsts: Foo
#     FromNamespacePatterns:
#       - \ABar(\W|\z)

class Bar
  # Bad. Cannot refer Foo from Bar namespace
  Foo
end

Instance Method Summary collapse

Instance Method Details

#on_const(node) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rubocop/cop/dependency/over_boundary.rb', line 20

def on_const(node)
  const_name = node.const_name
  current_namespace =
    node
    .each_ancestor(:class, :module)
    .map { |a| a.defined_module_name }
    .reverse.join('::')

  if cop_config['Rules']
     .select { |rule|
       Array(rule['BannedConsts']).include?(const_name)
     }
     .any? { |rule|
       Array(rule['FromNamespacePatterns']).any? { |from_pattern|
         Regexp.new(from_pattern).match?(current_namespace)
       }
     }
    add_offense(node, message: "Const `#{const_name}` cannot use from namespace `#{current_namespace}`.")
  end
end