How to Give a Sub-Module the Same Name as a Top-Level Class

Ruby - Including two modules that both have a sub-module with the same name

You can always rename modules to not conflict:

Foo::FooErrors = Foo::Errors
Bar::BarErrors = Bar::Errors

Or you could skip the conflicting modules and go straight to including the error classes you want:

class Baz
include Foo::Errors
include Bar::Errors
end

Or don't bother including anything and use the full names:

p Foo::Errors::FooError.new
p Bar::Errors::BarError.new

In my opinion, include is too often used as a convenience method to avoid typing module names. This usage is not really necessary and can introduce errors (as you've seen) or ambiguity. There are some things that you can only accomplish using include (like adding instance methods from a module), but most uses I see don't fall in that camp.

How do I include a module in a namespaced class?

Use :: to force the lookup to the top level only:

module Bar
class Foo
include ::Foo::Baz
end
end


Related Topics



Leave a reply



Submit