Module: NameMagic::ClassMethods
- Defined in:
- lib/y_support/name_magic.rb
Instance Method Summary collapse
-
#new(*args, &block) ⇒ Object
In addition to ‘constant magic’ ability (name upon constant assignment), NameMagic redefines class method #new so that it eats parameter :name, alias :ɴ, and takes care of naming the instance accordingly.
-
#new!(*args, &block) ⇒ Object
Calls #new in avid mode (name_avid: true).
Instance Method Details
#new(*args, &block) ⇒ Object
In addition to ‘constant magic’ ability (name upon constant assignment), NameMagic redefines class method #new so that it eats parameter :name, alias :ɴ, and takes care of naming the instance accordingly. Option :name_avid can also be supplied (true/false), which makes the naming avid if true. (Avid, or aggresive naming means that the instance being named overwrites whatever was stored under that name earlier.)
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'lib/y_support/name_magic.rb', line 347 def new *args, &block oo = args[-1].is_a?( Hash ) ? args.pop : {} # extract hash ɴß = if oo[:name] then oo.delete :name # consume :name if supplied elsif oo[:ɴ] then oo.delete :ɴ # consume :ɴ if supplied else nil end avid = oo[:name_avid] ? oo.delete( :name_avid ) : false # => true/false # Avoid overwriting existing names unless avid: raise NameError, "#{self} instance #{ɴß} already exists!" if __instances__.keys.include? ɴß unless avid # Instantiate: args << oo unless oo.empty? # fuse hash new_inst = original_method_new *args, &block __instances__.merge! new_inst => nil # Instance is created unnamed # honor the hook @new_instance_closure.( new_inst ) if @new_instance_closure if ɴß then # name was supplied, name the instance if avid then new_inst.name! ɴß else new_inst.name = ɴß end else # name wasn't supplied, make the instance avid __avid_instances__ << new_inst end return new_inst # return the new instance end |