Reputation: 688
I am using Ruby to create some simple project, and I am following RubyGems project structure. In my codebase I have two classes in different "namespaces":
lib
u
x
class_a.rb
m
p
class_b.rb
I am using nested modules for this classes, so ClassA is in module X which is in module U.
While requiring ClassA
inside ClassB
I can use it by referecing it with U::X::ClassA
. I wonder if there is any pattern that will let me just typing ClassA
, without full namespace.
Upvotes: 0
Views: 369
Reputation: 27885
Two comments in advance:
That said, you may build a minimal example like this:
module U
module X
class Class_a
end
end
end
module M
module P
class Class_b
include U::X
def initialize
a = U::X::Class_a.new ##you want replace this with:
#a= Class_a.new
end
end
end
end
M::P::Class_b.new
Fedes solution with Class_a = U::X::Class_a
would look like:
module U
module X
class Class_a
end
end
end
module M
module P
Class_a = U::X::Class_a ##<- define here the local version
class Class_b
def initialize
a= Class_a.new
end
end
end
end
M::P::Class_b.new
Another possibility is to include the module that contains the class:
module U
module X
class Class_a
end
end
end
module M
module P
class Class_b
include U::X #<- Include the module
def initialize
a= Class_a.new
end
end
end
end
M::P::Class_b.new
Attention: This solution will include all classes and constants of the module U::X
. This may be a solution you need, but it may also be wrong for your purpose.
Upvotes: 0
Reputation: 494
You can do something like
module M::P
ClassA = U::X::ClassA
end
defining ClassA
as a constant inside P
. It's not a good practise, but you can do it..
IMO, just use U::X::ClassA
.
Upvotes: 1