What is the difference in :: ModuleName :: ClassName and ModuleName :: ClassName

In ruby, I'm starting to see pretty normal practice, including modules and mixins, referenced as :: ModuleName :: ClassName, where before it was pretty much just ModuleName :: ClassName.

What I would like to get here is a worthy understanding of why this practice has been considered recently and what it does differently.

What's the difference?

What is the advantage (if the previous one does not answer this)?

Thank you in advance for your entry.

+6
source share
2 answers

If you put :: at the beginning, you are referencing the global namespace; if you do not, you are referring to your current namespace.

Usually, if you do not have a class / module with the same name inside your class / module, you will not need to use :: at 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

 Customer within order Customer global 
+9
source

When you do ::ModuleName::ClassName , you say:

I want you to look for ::ModuleName::ClassName in the root namespace, ignoring whether this code is inside another module. That way, he will always look for a class named ::ModuleName::ClassName and nothing else

When you say this: ModuleName::ClassName , you say:

I want you to look for ModuleName::ClassName , but first look at the current area and then at other areas. So, if you have a module called MyModule and this module refers to ModuleName::ClassName , first try to find MyModule::ModuleName::ClassName , then try to enable ::ModuleName::ClassName .

When I define such code, I almost always use :: ModuleName :: ClassName to avoid name conflicts.

+2
source

Source: https://habr.com/ru/post/909092/


All Articles