class RuboCop::Cop::Packaging::RequireRelativeHardcodingLib
require_relative “baz/qux”
require_relative “foo/bar/bax”
# good
require “foo/bar”
# good
require_relative “../../lib/foo/bar”
# bad
require “foo”
# good
require_relative “lib/foo”
# bad
@example
the gemspec file, and suggests to use ‘require` instead.
mapping to the “lib” directory, except originating from lib/ or
This cop flags the `require_relative` calls, from anywhere
:nodoc:
:nodoc:
:nodoc:
def falls_in_lib?(str)
It flags an offense if the `require_relative` call is made
This method is called from inside `#def_node_matcher`.
def falls_in_lib?(str) @str = str target_falls_in_lib?(str) && inspected_file_is_not_in_lib_or_gemspec? end
def good_require_call
Called from on_send, this method helps to replace the
def good_require_call good_call = File.expand_path(@str, @file_directory).delete_prefix("#{root_dir}/lib/") %(require "#{good_call}") end
def on_new_investigation
https://github.com/rubocop-hq/rubocop/blob/343f62e4555be0470326f47af219689e21c61a37/lib/rubocop/cop/base.rb
More about the `#on_new_investigation` method can be found here:
Extended from the Base class.
def on_new_investigation @file_path = processed_source.file_path @file_directory = File.dirname(@file_path) end
def on_send(node)
More about the `#on_send` method can be found here:
Extended from AST::Traversal.
def on_send(node) return unless require_relative(node) add_offense(node) do |corrector| corrector.replace(node, good_require_call) end end