Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/irb/command/load.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ def execute(arg)
def execute_internal(file_name = nil)
raise_cmd_argument_error unless file_name

rex = Regexp.new("(?:\\A|/)#{Regexp.escape(file_name)}(?:\\.o|\\.rb)?\\z")
return false if $".find{|f| f =~ rex}
return false if already_loaded?(file_name)

case file_name
when /\.rb$/
Expand All @@ -69,6 +68,19 @@ def execute_internal(file_name = nil)
require(file_name)
end
end

private

# $" holds the names irb_require pushed and the absolute paths that
# Kernel#require loaded from a $LOAD_PATH directory.
def already_loaded?(file_name)
names = [file_name, "#{file_name}.rb", "#{file_name}.o"]
paths = $LOAD_PATH.flat_map do |dir|
dir = dir.to_s
names.map { |name| File.expand_path(File.join(dir, name)) }
end
$".any? { |f| names.include?(f) || paths.include?(f) }
end
end

class Source < LoaderCommand
Expand Down
15 changes: 15 additions & 0 deletions test/irb/test_command.rb
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,21 @@ def test_irb_require_skips_file_already_loaded_by_require
assert_match(/prefix_loaded/, out)
end

def test_irb_require_loads_file_with_same_name_as_loaded_file_in_other_directory
Dir.mkdir("#{@tmpdir}/sub")
File.write("#{@tmpdir}/sub/irb_require_same.rb", "$irb_require_same_sub = true\n")
File.write("#{@tmpdir}/irb_require_same.rb", "'top_loaded'\n")

out, err = execute_lines(
"$LOAD_PATH.unshift '#{@tmpdir}'\n",
"require 'sub/irb_require_same'\n",
"irb_require 'irb_require_same'\n",
)

assert_empty(err)
assert_match(/top_loaded/, out)
end

def test_irb_require_falls_back_to_kernel_require_when_not_in_load_path
code = <<~RUBY
p 'fallback_loaded'
Expand Down
Loading