Rojo
6/11/2018 - 10:56 PM

A #require_relative_with_tco that's like #require_relative but with tail call optimization

A #require_relative_with_tco that's like #require_relative but with tail call optimization

module Kernel
  def require_relative_with_tco file
    absolute_path = File.absolute_path file, __dir__
    realpath = File.realpath "#{absolute_path.chomp '.rb'}.rb"

    if $LOADED_FEATURES.include? realpath
      false
    else
      RubyVM::InstructionSequence.compile_file(
        realpath,
        tailcall_optimization: true,
        trace_instruction: false
      ).eval

      $LOADED_FEATURES << realpath

      true
    end

  rescue Errno::ENOTDIR, Errno::ENOENT
    raise LoadError, "cannot load such file -- #{absolute_path}"
  end
end