Last active
September 14, 2021 04:22
-
-
Save havenwood/3c5a5e1476c811460992 to your computer and use it in GitHub Desktop.
A #require_relative_with_tco that's like #require_relative but with tail call optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment