[ruby-core:112773] [Ruby master Feature#19521] Support for `Module#name=` and `Class#name=`.
From:
"ioquatix (Samuel Williams) via ruby-core" <ruby-core@...>
Date:
2023-03-09 08:59:15 UTC
List:
ruby-core #112773
Issue #19521 has been reported by ioquatix (Samuel Williams).
----------------------------------------
Feature #19521: Support for `Module#name=` and `Class#name=`.
https://bugs.ruby-lang.org/issues/19521
* Author: ioquatix (Samuel Williams)
* Status: Open
* Priority: Normal
----------------------------------------
See https://bugs.ruby-lang.org/issues/19450 for previous discussion and motivation.
This proposal introduces `Class#name=` to set the temporary class name. This is an alternative or addition to <https://bugs.ruby-lang.org/issues/19520>.
```ruby
c = Class.new do
self.name = "fake name"
end
c = Class.new
c.name = "fake name"
```
Alternatively, we could use `set_name`:
```ruby
Class.new do
set_name "fake_name"
end
```
## Example usage
The current Ruby test suite has code which shows the usefulness of this new method:
```ruby
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:
```ruby
def labeled_module(name, &block)
Module.new do
self.name = name
class_eval(&block) if block
end
end
def labeled_class(name, superclass = Object, &block)
Class.new(superclass) do
self.name = name
class_eval(&block) if block
end
end
module_function :labeled_class
```
Because the name cannot be set as part of `.new`, we have to have a separate block to set the name, before calling `class_eval`. I think the ergonomics and performance of this are slightly worse than the [counter proposal](https://bugs.ruby-lang.org/issues/19520).
--
https://bugs.ruby-lang.org/
______________________________________________
ruby-core mailing list -- ruby-core@ml.ruby-lang.org
To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/