Class: RuboCop::Cop::Airbnb::ClassOrModuleDeclaredInWrongFile

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

Overview

This cop checks for a class or module declared in a file that does not match its name. 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.

Note that autoloading works fine if classes are defined in the file that defines the module. This is common usage for things like error classes, so we’ll allow it. Nested classes are also allowed:

Examples:

# bad

# foo/bar.rb
module Foo
  class Goop
  end

  module Moo
  end
end

# good

# foo.rb

# foo/goop.rb
module Foo
  class Goop
  end
end

# foo/moo.rb
module Foo
  module Moo
  end
end
# good

# foo.rb
module Foo
  class Bar < StandardError
  end
end

# good

# foo.rb
class Foo
  class Bar # nested class
  end
end

Constant Summary collapse

CLASS_OR_MODULE_MSG =

class Foo or module Foo in the wrong file

"In order for Rails autoloading to be able to find and load this file when " \
"someone references this class/module, move its definition to a file that matches " \
"its name. %s %s should be defined in %s.".freeze
ERROR_CLASS_MSG =

class FooError < StandardError, in the wrong file

"In order for Rails autoloading to be able to find and load this file when " \
"someone references this class, move its definition to a file that defines " \
"the owning module. Class %s should be 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_class(node) ⇒ Object

class C



80
81
82
# File 'lib/rubocop/cop/airbnb/class_or_module_declared_in_wrong_file.rb', line 80

def on_class(node)
  on_class_or_module(node)
end

#on_module(node) ⇒ Object

module M



75
76
77
# File 'lib/rubocop/cop/airbnb/class_or_module_declared_in_wrong_file.rb', line 75

def on_module(node)
  on_class_or_module(node)
end