Class: RuboCop::Cop::Airbnb::ModuleMethodInWrongFile

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

Overview

This cop checks for methods defined in a module declaration, in a file that doesn’t match the module name. The Rails autoloader can’t find such a method, 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:

Examples:

# bad

# foo/bar.rb
module Foo
  class Bar
  end

  def baz
    42
  end
end

# good

# foo/bar.rb
module Foo
  class Bar
  end
end

# foo.rb
module Foo
  def baz
    42
  end
end
# good

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

# good

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

Constant Summary collapse

MSG_TEMPLATE =
"In order for Rails autoloading to be able to find and load this file when " \
"someone calls this method, move the method definition to a file that defines " \
"the module. This file just uses the module as a namespace for another class " \
"or module. Method %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_def(node) ⇒ Object Also known as: on_defs



72
73
74
75
# File 'lib/rubocop/cop/airbnb/module_method_in_wrong_file.rb', line 72

def on_def(node)
  method_name, args, body = *node
  on_method_def(node, method_name, args, body)
end