What are the consequences of a class name A :: B in a ruby?

I have an Entity class, and inside this class I had an inner Config class.

class Entity class Config end end 

The Config class has become quite large, so I decided to take it to my own file. However, I still wanted to preserve the namespace, so I prefixed the Config class with Entity :: and left me two classes in two different files, for example:

  #In entity.rb file class Entity require 'entity_config.rb' end #In entity_config.rb file class Entity::Config end 

Now I can create a configuration with Entity :: Config.new

However, I do not understand the meaning of the names that call this class name. Can someone explain to me what is really going on here?

+4
source share
1 answer

When you write class Something , you provide Something a constant name, so providing the name with the :: operator is equivalent to opening an external class and creating this inner class. The :: operator is just a way to access a constant inside a class or module from outside this class or module. for example, something like this is quite fair:

 class Outer class Inner end class Inner::EvenMoreInner end end class Outer::Inner::EvenMoreInner::InnerMost end 

Note: you cannot just write class Some::New::Class::Hierarchy and create all contained classes automatically. i.e., Some::New::Class must exist first. This is why I requested the exact order of the code that you wrote in my comment on the question.

+4
source

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


All Articles