Issue #7149 has been updated by boris_stitnicky (Boris Stitnicky).


Since I have put my library in public, I can to exemplify the idea:
https://github.com/boris-s/y_support

After installing:

require 'y_support/name_magic'
class Klass; include NameMagic end
UJAK = Klass.new
Klass.instance_names    #=> [:UJAK]
UJAK.name               #=> :UJAK
Klass.new name :ANEC
Klass.instance_names    #=> [:UJAK, :ANEC]
Klass.instance( :ANEC ) == Klass::ANEC    #=> true
Klass.instance_names #=> [:UJAK, :ANEC, :VIAK]

I am too busy using the library to be working on its documentation, sorry.
I use this all the time, in expressions such as

Length = Quantity.standard of :L
# the above creates a Quantity instance named :Length with physical
# dimension :L

METRE = Unit.standard of: Length, short: "m"
# the above creates a physical unit named :metre (constant assignment
# alone is enough to convey the information about the unit name, and
# hook is used to downcase :METRE to :metre), so that 1.metre and 1.m
# both start working.

# more examples in https://github.com/boris-s/sy/blob/master/lib/sy.rb

----------------------------------------
Feature #7149: Constant magic for everyone.
https://bugs.ruby-lang.org/issues/7149#change-38507

Author: boris_stitnicky (Boris Stitnicky)
Status: Feedback
Priority: Normal
Assignee: 
Category: 
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/