class RuboCop::Cop::Packaging::RequireHardcodingLib
require “baz/qux”
# good
require File.dirname(__FILE__) + “/../../lib/baz/qux”
# bad
require “foo/bar/baz/qux”
# good
require File.expand_path(“../../../lib/foo/bar/baz/qux”, __dir__)
# bad
require “foo”
# good
require File.expand_path(“../../lib/foo”, __FILE__)
# bad
require “foo/bar”
# good
require “../lib/foo/bar”
# bad
@example
the “lib” directory, except originating from lib/.
This cop flags the ‘require` calls, from anywhere mapping to
:nodoc:
:nodoc:
:nodoc:
def falls_in_lib?(str)
It flags an offense if the `require` call is made from
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 falls_in_lib_using_file?(str)
It flags an offense if the `require` call (using the __FILE__
This method is called from inside `#def_node_matcher`.
def falls_in_lib_using_file?(str) @str = str target_falls_in_lib_using_file?(str) && inspected_file_is_not_in_lib_or_gemspec? end
def falls_in_lib_with_file_dirname_plus_str?(str)
This method preprends a "." to the string that starts with "/".
def falls_in_lib_with_file_dirname_plus_str?(str) @str = str str.prepend(".") 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
def good_require_call good_call = @str.sub(%r{^.*/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?(node) add_offense(node) do |corrector| corrector.replace(node, good_require_call) end end