From: "marcandre (Marc-Andre Lafortune)" Date: 2013-04-13T05:27:53+09:00 Subject: [ruby-core:54244] [ruby-trunk - Feature #7149][Open] Constant magic for everyone. Issue #7149 has been updated by marcandre (Marc-Andre Lafortune). Category set to core Status changed from Feedback to Open Assignee set to matz (Yukihiro Matsumoto) I've never needed this, but I could envision a `const_assigned` callback. Whenever a constant is assigned to an object, then object.const_assigned("FullyQualified::Name") would be called. In other words, the "magic" around Modules and Classes could be understood with the "equivalent" Ruby code: class Module def const_assigned(name) @name ||= name end def to_s @name || "#" end end I would guess that the runtime impact would be completely negligible. In the examples given above, ChemicalSpecies could have a similar method. And yes, even (6*7).name could be "Foo::Bar" with: class Fixnum @@reg = {} def name @@reg[self] || to_s end def const_assigned(name) @@reg[self] ||= name end end > What do you expect if the object is assigned to two or more constants? That would be entirely up to the implementer of `const_assigned`, but `const_assigned` would be called multiple times. ---------------------------------------- Feature #7149: Constant magic for everyone. https://bugs.ruby-lang.org/issues/7149#change-38508 Author: boris_stitnicky (Boris Stitnicky) Status: Open Priority: Normal Assignee: matz (Yukihiro Matsumoto) Category: core Target version: next minor I noticed that certain objects have constant magic: When they are first assigned to a constant, they acquire a name property equal to the constant name string. I only know about Class and Struct objects behaving this way. I like this behavior, because I like to be able to say something like: Adenosine = ChemicalSpecies.new initial_concentration: 5.micromolar Adenosine.name #=> "Adenosine" I like it so much, that I wrote a library (I call it ConstantMagicErsatz) for myself that searches whole namespace for the new objects assigned to constants. But searching whole wild namespace has its pitfalls. It is a wildly difficult workaround to get the candy I want. I am dreaming about just being able to say: class ChemicalSpecies constant_magic true end and imbue ChemicalSpecies with the same constant magic ability that Class and Struct classes have. Could it be made possible, please? -- http://bugs.ruby-lang.org/