In ruby, I'm starting to see a pretty normal practice including modules and mixins referenced as ::ModuleName::ClassName, where in the past it was pretty much just ModuleName::ClassName.
What I'd like to get here is a decent understanding of why this practice is being seen more lately and what it does differently.
What's the difference?
What's the benefit (if the prior doesn't answer this)?
Thanks in advance for your input.
If you put the ::
in the beginning you are referring to the global namespace, if you don't you are referring to your current namespace.
Usually if you don't have a class/module with the same name inside your class/module you would not need to use the ::
in the beginning.
class Customer
def to_s
"Customer global"
end
end
class Order
class Customer
def to_s
"Customer within order"
end
end
def initialize
puts Customer.new
puts ::Customer.new
end
end
Order.new
will print out
Customer within order
Customer global
When you do ::ModuleName::ClassName
you're saying:
I want you to look for
::ModuleName::ClassName
at the root namespace, ignoring if this code is found inside another module. So, it will always look for a class that's named as::ModuleName::ClassName
and nothing else
When you say it like this ModuleName::ClassName
, you're saying:
I want you to look for
ModuleName::ClassName
but looking at the current scope first and then at the other scopes. So, if you have a module called MyModule and this my module referencesModuleName::ClassName
then first try to findMyModule::ModuleName::ClassName
then try to resolve::ModuleName::ClassName
.
When I'm defining code like this I almost always use ::ModuleName::ClassName to avoid any naming conflicts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With