[ruby-core:112881] [Ruby master Feature#19520] Support for `Module.new(name)` and `Class.new(superclass, name)`.
From:
"Eregon (Benoit Daloze) via ruby-core" <ruby-core@...>
Date:
2023-03-14 20:58:16 UTC
List:
ruby-core #112881
Issue #19520 has been updated by Eregon (Benoit Daloze).
Another thought: maybe a much simpler way to solve most of these use-cases is adding `Module#source_location`, which is the `[file, line]` at which the Module was created.
That could also work for anonymous modules, they could capture at which file, line `Module.new` was called.
That I think would remove the need to label modules/classes in tests, since the file line would then refer to where it was created, and at that file:line there is likely a local variable which makes it clear what's the role of this anonymous module/class.
The anonymous reloading use-case would also be helped by having that file path attached to anonymous modules.
We could then maybe show this file:line automatically for Module#inspect and in exception messages if the module is anonymous.
If the module is named it's likely of much lower value so there probably not change anything, but anyone could still call `Module#source_location` to find more about the module/class at hand.
----------------------------------------
Feature #19520: Support for `Module.new(name)` and `Class.new(superclass, name)`.
https://bugs.ruby-lang.org/issues/19520#change-102397
* Author: ioquatix (Samuel Williams)
* Status: Open
* Priority: Normal
----------------------------------------
See <https://bugs.ruby-lang.org/issues/19450> for previous discussion and motivation.
[This proposal](https://github.com/ruby/ruby/pull/7376) introduces the `name` parameter to `Class.new` and `Module.new`:
```ruby
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:
```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(name, &block)
end
def labeled_class(name, superclass = Object, &block)
Class.new(superclass, name, &block)
end
module_function :labeled_class
```
--
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/