Maksym Bykovskyy
Maksym Bykovskyy

Reputation: 832

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

I have a class Entity and inside this class I used to have an inner class called Config.

class Entity
 class Config
 end
end

The Config class has grown quite big so I decided to take it out into its own file. However, I still wanted to retain the namespace so I prefixed the Config class with an Entity:: leaving me with two class in two different files like so.

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

 #In entity_config.rb file
 class Entity::Config
 end

Now I'm able to instantiate config with Entity::Config.new

However, I don't understand the implications of namespacing the class name like that. Can somebody explain to me what really happens here?

Upvotes: 4

Views: 172

Answers (1)

mikej
mikej

Reputation: 66263

When you write class Something the Something you're providing is the name of a constant so providing the name using the :: operator is equivalent to opening the outer class first and creating an inner class that way. The :: operator is just a way to access a constant within a class or module from outside of that class or module. e.g. something like this is completely valid:

class Outer
  class Inner
  end

  class Inner::EvenMoreInner
  end
end

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

Notice, you can't just write class Some::New::Class::Hierarchy and have all the containing classes created automatically. i.e. Some::New::Class must exist first. This is why I queried the exact order of the code you've written in my comment on the question.

Upvotes: 4

Related Questions