Skip to content

Commit

Permalink
Let push_dir raise if given an anonymous root namespace
Browse files Browse the repository at this point in the history
Anonymous root namespaces are not supported, Zeitwerk assumes classes and
modules have regular names in a few places.

However, if you pass an anonymous root namespace right now the library crashes
in some random internal spot. It is better to tell the user at the boundary and
in a controlled way. Also, this allows us to work internally knowing that root
namespaces in `roots` have a name for sure.
  • Loading branch information
fxn committed Nov 3, 2022
1 parent a0bd943 commit f3a43e5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/zeitwerk/loader/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

module Zeitwerk::Loader::Config
extend Zeitwerk::Internal
include Zeitwerk::RealModName

# @sig #camelize
attr_accessor :inflector
Expand Down Expand Up @@ -113,6 +114,10 @@ def push_dir(path, namespace: Object)
raise Zeitwerk::Error, "#{namespace.inspect} is not a class or module object, should be"
end

unless real_mod_name(namespace)
raise Zeitwerk::Error, "root namespaces cannot be anonymous"
end

abspath = File.expand_path(path)
if dir?(abspath)
raise_if_conflicting_directory(abspath)
Expand Down
5 changes: 5 additions & 0 deletions test/lib/zeitwerk/test_push_dir.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,9 @@ def check_dirs
e = assert_raises(Zeitwerk::Error) { loader.push_dir(".", namespace: :foo) }
assert_equal ":foo is not a class or module object, should be", e.message
end

test "raises if the namespace is anonymous" do
e = assert_raises(Zeitwerk::Error) { loader.push_dir(".", namespace: Module.new) }
assert_equal "root namespaces cannot be anonymous", e.message
end
end

0 comments on commit f3a43e5

Please sign in to comment.