Class: RuboCop::Cop::Packaging::RelativeRequireToLib

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/packaging/relative_require_to_lib.rb

Overview

This cop is used to identify the require_relative calls, mapping to the “lib” directory and suggests to use require instead.

Examples:


# bad
require_relative 'lib/foo.rb'

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

# good
require 'foo.rb'

# good
require 'foo/bar'

# good
require_relative 'spec_helper'
require_relative '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

Instance Method Details

#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.



44
45
46
47
# File 'lib/rubocop/cop/packaging/relative_require_to_lib.rb', line 44

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



52
53
54
55
56
# File 'lib/rubocop/cop/packaging/relative_require_to_lib.rb', line 52

def on_send(node)
  return unless require_relative(node)

  add_offense(node)
end

#target_falls_in_lib?(str) ⇒ Boolean

This method is called from inside #def_node_matcher. It is used to find paths which starts with “lib”.

Returns:

  • (Boolean)


60
61
62
63
# File 'lib/rubocop/cop/packaging/relative_require_to_lib.rb', line 60

def target_falls_in_lib?(str)
  root_dir = RuboCop::ConfigLoader.project_root
  File.expand_path(str, @file_directory).start_with?(root_dir + '/lib')
end