Code style preference when nesting modules

I got a beat, suggesting that

module A module B end end 

and

 module A::B end 

are the same. I managed to find a solution to this blog , this SO stream , and this SO stream .

Why and when should the compact A::B syntax be preferred over the other, given that it clearly has a flaw? I have an intuition that this may be related to performance, since finding constants in a larger namespace requires more calculations. But I could not verify this by comparing ordinary classes.

+5
source share
2 answers

These two writing methods are often confused.

First of all, I must say that, as far as I know, there is no measurable difference in performance. (one constant search in the example below)

The most obvious difference, perhaps the most famous, is that for the second example ( module A::B ), it is required for module A exist during the definition.

Otherwise, most people consider them interchangeable. This is not true .

Modules are just constants in ruby ​​and therefore regular, constant searches are applied.

Let me show this with an example:

 module A class Test end module B class Show p Module.nesting # =>[A::B::Show, A::B, A] def show_action Test.respond_with(%q(I'm here!)) end end end end 

On the other hand, if you call it through A::B , see what happens:

 module A class Test end end module A::B class Show p Module.nesting # => [A::B::Show, A::B] def show_action Test.respond_with(%q(I'm here!)) end end end 

The difference is that .nesting produces:

1) in the first case: [A::B::Show, A::B, A] (you are nested in module A )

2) in the second case: [A::B::Show, A::B] (not here)

+7
source

The first has more information than the second. Naturally, in most cases, you can assume that the second form can always be replaced by the first, but not vice versa. In fact, you cannot use the second form unless A is predefined. But be careful that the return values ​​of Module#nesting differ between the two forms, as the method has a lexical interpretation of the scope.

+1
source

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


All Articles