Class: RuboCop::Cop::Packaging::RequireRelativeHardcodingLib

Inherits:
Base
  • Object
show all
Includes:
Packaging::LibHelperModule
Defined in:
lib/rubocop/cop/packaging/require_relative_hardcoding_lib.rb

Overview

This cop flags the require_relative calls, from anywhere mapping to the “lib” directory, except originating from lib/ or the gemspec file, and suggests to use require instead.

Examples:


# bad
require_relative "lib/foo.rb"

# good
require "foo.rb"

# bad
require_relative "../../lib/foo/bar"

# good
require "foo/bar"

# good
require_relative "spec_helper"
require_relative "spec/foo/bar"

Constant Summary collapse

MSG =

This is the message that will be displayed when RuboCop finds an offense of using require_relative with relative path to lib.

"Avoid using `require_relative` with relative path to lib. " \
"Use `require` instead."

Instance Method Summary collapse

Methods included from Packaging::LibHelperModule

#inspected_file_falls_in_lib?, #inspected_file_is_gemspec?, #root_dir, #target_falls_in_lib?, #target_falls_in_lib_using_file?

Instance Method Details

#falls_in_lib?(str) ⇒ Boolean

This method is called from inside #def_node_matcher. It flags an offense if the require_relative call is made from anywhere except the “lib” directory.

Returns:

  • (Boolean)


65
66
67
# File 'lib/rubocop/cop/packaging/require_relative_hardcoding_lib.rb', line 65

def falls_in_lib?(str)
  target_falls_in_lib?(str) && !inspected_file_falls_in_lib? && !inspected_file_is_gemspec?
end

#on_new_investigationObject

Extended from the Base class. More about the #on_new_investigation method can be found here: github.com/rubocop-hq/rubocop/blob/343f62e4555be0470326f47af219689e21c61a37/lib/rubocop/cop/base.rb

Processing of the AST happens here.



48
49
50
51
# File 'lib/rubocop/cop/packaging/require_relative_hardcoding_lib.rb', line 48

def on_new_investigation
  @file_path = processed_source.file_path
  @file_directory = File.dirname(@file_path)
end

#on_send(node) ⇒ Object

Extended from AST::Traversal. More about the #on_send method can be found here: github.com/rubocop-hq/rubocop-ast/blob/08d0f49a47af1e9a30a6d8f67533ba793c843d67/lib/rubocop/ast/traversal.rb#L112



56
57
58
59
60
# File 'lib/rubocop/cop/packaging/require_relative_hardcoding_lib.rb', line 56

def on_send(node)
  return unless require_relative(node)

  add_offense(node)
end