Re: How does the class name magic with Class.new?

Xavier Noria <[email protected]> Mon, 10 Jun 2019 08:34:28 +0200
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CAM=YcdgZ2TO=h5WoYsN-1fG6YPW+iMsaHRH0JpW6r_E2JKOWXg@mail.gmail.com>
The class keyword does the same behind the scenes, it creates a class
object and assigns it to a constant. The name is set as a side-effect just
like you saw doing it by hand.

It's interesting to note that there is no API to manipulate this name, but
at the same time the name is independent of the constant from that point
on. Indeed, you can even remove the original constant, and the name of the
class is still "C":

irb(main):001:0> C = Class.new
=> C
irb(main):002:0> C.name
=> "C"
irb(main):003:0> D = C
=> C
irb(main):004:0> Object.send(:remove_const, :C)
=> C
irb(main):005:0> D.name
=> "C"
irb(main):006:0> D
=> C

Besides, if you reopen D, you are reopening the class with name "C", because

class D
end

is not about the constant you see in the listing, Ruby checks if the
constant is defined, and if so it *reopens the class object it contains*,
regardless of its name. You reopen class objects, not constants.

This connection and disconnection class/module objects vs constants makes
constants a topic full of non-intuitive technical possibilities if you're
only used to the golden path in which all matches.

That is why Zeitwerk requires a certain project structure and basically
restricts things to that golden path, by limiting what you can do, it makes
autoloading solvable.


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>