Private classes in Ruby

Constants can be declared private explicitly (Private constants in Ruby). The same holds true for classes.

Why private?

Sometimes it makes sense, to define private classes. For instance if particular logic has to be moved into a concerning class for encapsulation reasons. Then it is not necessary to leave the class as public.
A Product class is a reasonable example. Each product is characterized by its specific serial number.
However the Product class is not responsible for generating the serial number. It makes sense to encapsulate the logic into a separate Serial class. Even more, if the serial number includes further logic:

class Product
  class Serial
    def initialize
      @date = Date.today
    end

    def code
      "#{@date}/#{object_id}"
    end
  end

  attr_reader :serial

  def initialize
    @serial = Serial.new
  end

  def code
    serial.code
  end
end

A new product with a serial:

Product.new.code # => "2016-06-19/32713960"

Though the class Serial is externally accessible:

Product::Serial.new # => #<Product::Serial:0x00000002be1548 ... >

It always holds true for public: as little as possible, as much as necessary.

Therefore private!

class Product
  class Serial
    def initialize
      @date = Date.today
    end

    def code
      "#{@date}/#{object_id}"
    end
  end

  # explizit privat:
  private_constant :Serial

  attr_reader :serial

  def initialize
    @serial = Serial.new
  end

  def code
    serial.code
  end
end

The class Serial is declared private by use of Module#private_constant. That is why it can not be instantiated directly anymore:

Product::Serial.new
# => NameError: private constant Product::Serial referenced