How to access parent / sibling module methods

Is there a way to access baz_method inside a baz_method class Qux without mentioning the module namespace the first time? When there are many nested modules, the code does not look clean.

 module Foo module Bar module Baz class Qux def self.qux_method Foo::Bar::Baz.baz_method end end def self.baz_method end end end end 
+5
source share
3 answers

Constants are viewed first in the lexically covering module (s), and then up the inheritance chain.

 module Foo module Bar module Baz class Qux def self.qux_method Baz.baz_method end end def self.baz_method end end end end 

This will work because the Baz constant will be first examined in the lexically closing Qux module (class), where it will not be found. The search continues in the lexically closing Baz module, where it is also not found. Therefore, it will look in the lexically closing Bar module, where it will be found and the search will be stopped.

Note: you write in your title:

Ruby, parent / child module access methods

It is not right. These modules are neither parents nor siblings. There is no inheritance. In fact, there is no connection between the modules. There is only a relationship between constants and modules: constants belong to modules.

Module declarations are lexically nested, but the modules themselves are not.

+9
source

You do not need to specify the entire chain of the namespace. You need as much as you need to disambiguate the constant. Just use Baz.baz_method .

 module Foo module Bar module Baz class Qux def self.qux_method Baz.baz_method end end def self.baz_method end end end end 
+4
source

Note Unless you are explicitly looking for relative access to the module, this metaprogramming is not necessary. Use @drhining instead.

You can dynamically climb the hierarchy of modules with Module#nesting :

 module Foo module Bar module Baz class Qux def self.qux_method Module.nesting[1].baz_method end end def self.baz_method puts "foo!" end end end end 

In this situation, Module.nesting will give the following (if called in qux_method ): [Foo::Bar::Baz::Qux, Foo::Bar::Baz, Foo::Bar, Foo]

Please note that this is not an unambiguous reference to Baz , but to what happens in one module in the module chain.

+2
source

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


All Articles