Search code examples
rubykerneloverloadingrequire

Overloading Kernel.require() without braking it


I'm trying to overload the Kernel.require() method to get data required to build code dependency tree. This is how I simply imagine the new require method:

def require arg
  super arg
  puts "including '#{arg}' in '#{caller_locations(1).first.path}'"
end

Unfortunately, I found this to be braking the require() invocation somewhere else in the code causing the sequence of errors.


Solution

  • The original implementation of Kernel#require returns true or false. Your new require method does not return that value anymore instead it always returns nil (the response from the p method).

    I can imagine that in some cases it makes sense to have a condition in your code and define constants depending on the response of the require.

    You can probably fix the issue by swapping the lines in your method:

    def require(name)
      puts "requiring '#{name}' in '#{caller_locations(1).first.path}'"
      super
    end