Class: RuboCop::Cop::Airbnb::ConstAssignedInWrongFile

Inherits:
Base
  • Object
show all
Includes:
Inflections, RailsAutoloading
Defined in:
lib/rubocop/cop/airbnb/const_assigned_in_wrong_file.rb

Overview

This cop checks for a constant assigned in a file that does not match its owning scope. The Rails autoloader can’t find such a constant, but sometimes people “get lucky” if the file happened to be loaded before the method was defined.

Examples:

# bad

# foo/bar.rb
module Foo
  BAZ = 42
end

# good

# foo.rb
module Foo
  BAZ = 42
end

Constant Summary collapse

ASSIGNMENT_MSG =

FOO = 42

"In order for Rails autoloading to be able to find and load this file when " \
"someone references this const, move the const assignment to a file that defines " \
"the owning module. Const %s should be defined in %s.".freeze
GLOBAL_ASSIGNMENT =

FOO = 42 at global scope

"In order for Rails autoloading to be able to find and load this file when " \
"someone references this const, move the const assignment to a file that defines " \
"the owning module. Const %s should be moved into a namespace or defined in %s.".freeze

Instance Method Summary collapse

Methods included from RailsAutoloading

#allowable_paths_for, #full_const_name, #normalize_module_name, #run_rails_autoloading_cops?, #split_modules

Methods included from Inflections

#underscore

Instance Method Details

#on_casgn(node) ⇒ Object

FOO = 42



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/airbnb/const_assigned_in_wrong_file.rb', line 41

def on_casgn(node)
  path = node.source_range.source_buffer.name
  return unless run_rails_autoloading_cops?(path)
  return unless node.parent_module_name

  # Ignore assignments like Foo::Bar = 42
  return if node.children[0]

  const_name = node.children[1]
  parent_module_name = normalize_module_name(node.parent_module_name)
  fully_qualified_const_name = full_const_name(parent_module_name, const_name)
  expected_dir = underscore(fully_qualified_const_name)
  allowable_paths = allowable_paths_for(expected_dir)
  if allowable_paths.none? { |allowable_path| path =~ allowable_path }
    add_error(const_name, node)
  end
end