Project

General

Profile

Actions

Feature #19520

closed

Support for `Module.new(name)` and `Class.new(superclass, name)`.

Added by ioquatix (Samuel Williams) about 1 year ago. Updated 11 months ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:112770]

Description

See https://bugs.ruby-lang.org/issues/19450 for previous discussion and motivation.

This proposal introduces the name parameter to Class.new and Module.new:

Class.new(superclass, name)
Module.new(name)

As a slight change, we could use keyword arguments instead.

Example usage

The current Ruby test suite has code which shows the usefulness of this new method:

  def labeled_module(name, &block)
    Module.new do
      singleton_class.class_eval {
        define_method(:to_s) {name}
        alias inspect to_s
        alias name to_s
      }
      class_eval(&block) if block
    end
  end
  module_function :labeled_module

  def labeled_class(name, superclass = Object, &block)
    Class.new(superclass) do
      singleton_class.class_eval {
        define_method(:to_s) {name}
        alias inspect to_s
        alias name to_s
      }
      class_eval(&block) if block
    end
  end
  module_function :labeled_class

The updated code would look like this:

  def labeled_module(name, &block)
    Module.new(name, &block)
  end

  def labeled_class(name, superclass = Object, &block)
    Class.new(superclass, name, &block)
  end
  module_function :labeled_class

Related issues 3 (0 open3 closed)

Related to Ruby master - Feature #19521: Support for `Module#name=` and `Class#name=`.ClosedActions
Related to Ruby master - Feature #19450: Is there an official way to set a class name without setting a constant?ClosedActions
Related to Ruby master - Feature #18285: NoMethodError#message uses a lot of CPU/is really expensive to callClosedActions
Actions

Also available in: Atom PDF

Like1
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like1Like0Like1Like0Like0Like1Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0