Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
Module#set_temporary_name
VALUE
rb_mod_set_temporary_name(VALUE mod, VALUE name)
{
// We don't allow setting the name if the classpath is already permanent:
if (RCLASS_EXT(mod)->permanent_classpath) {
rb_raise(rb_eRuntimeError, "can't change permanent name");
}
if (NIL_P(name)) {
// Set the temporary classpath to NULL (anonymous):
RCLASS_SET_CLASSPATH(mod, 0, FALSE);
} else {
// Ensure the name is a string:
StringValue(name);
if (RSTRING_LEN(name) == 0) {
rb_raise(rb_eArgError, "empty class/module name");
}
if (is_constant_path(name)) {
rb_raise(rb_eArgError, "the temporary name must not be a constant path to avoid confusion");
}
// Set the temporary classpath to the given name:
RCLASS_SET_CLASSPATH(mod, name, FALSE);
}
return mod;
}
Sets the temporary name of the module. This name is reflected in introspection of the module and the values that are related to it, such as instances, constants, and methods.
The name should be nil or non-empty string that is not a valid constant name (to avoid confusing between permanent and temporary names).
The method can be useful to distinguish dynamically generated classes and modules without assigning them to constants.
If the module is given a permanent name by assigning it to a constant, the temporary name is discarded. A temporary name can’t be assigned to modules that have a permanent name.
If the given name is nil, the module becomes anonymous again.
Example:
m = Module.new # => #<Module:0x0000000102c68f38> m.name #=> nil m.set_temporary_name("fake_name") # => fake_name m.name #=> "fake_name" m.set_temporary_name(nil) # => #<Module:0x0000000102c68f38> m.name #=> nil c = Class.new c.set_temporary_name("MyClass(with description)") c.new # => #<MyClass(with description):0x0....> c::M = m c::M.name #=> "MyClass(with description)::M" # Assigning to a constant replaces the name with a permanent one C = c C.name #=> "C" C::M.name #=> "C::M" c.new # => #<C:0x0....>
Ruby version changes
-
3.3
-
Module#set_temporary_nameadded for setting a temporary name for a module. [Feature #19521]
-