我,強制性,將在這裏介紹my NameMagic
:
# first, gem install y_support
require 'y_support/name_magic'
class Person
include NameMagic
# here, Person receives for free the following functionality:
# * ability to use :name (alias :ɴ) named argument in the constructor
# * #name (alias #ɴ) instance method
# * #name= naming/renaming method
# * ability to name anonymous instances by merely assigning to constants
# * collection of both named and anonymous instances inside the namespace
# * hooks to modify the name, or do something else when the name is assigned
# * ability to specify a different namespace than mother class for instance collection
end
Joe = Person.new #=> #<Person:0xb7ca89f8>
Rick = Person.new #=> #<Person:0xb7ca57bc>
Joe.name #=> :Joe
Rick.ɴ #=> :Rick
Person.instances # [#<Person:0xb7ca89f8>, #<Person:0xb7ca57bc>]
Person.instance_names # [:Joe, :Rick]
Person.new name: "Kit" #=> #<Person:0xb9776244>
Person.instance_names #=> [:Joe, :Rick, :Kit]
p3 = Person.instance(:Kit) #=> #<Person:0xb9776244>
p2 = Person.instance("Rick") #=> #<Person:0xb7ca57bc>
# Also works if the argument is already a Person instance:
p1 = Person.instance(Person.instance(:Joe)) #=> #<Person:0xb9515ba8>
anon = Person.new #=> #<Person:0xb9955c54>
Person.instances.size #=> 4
Person.instance_names #=> [:Joe, :Rick, :Kit]
anon.name = :Hugo
Person.instance_names #=> [:Joe, :Rick, :Kit, :Hugo]
Person::Hugo #=> #<Person:0xb9955c54>
有關垃圾回收的擔憂,一個可以忘記實例
Person.forget :Hugo #=> Returns, for the last time, "Hugo" instance
Person::Hugo #=> NameError
Person.forget_all_instances #=> [:Joe, :Rick, :Kit]
Person.instances #=> [] - everything is free to be GCed
引擎蓋下NameMagic
使用相同的方法@sawa提議(至少在const_assigned
鉤子由Ruby核心開發者提供)之前,即搜索整個ObjectSpace
- 但不是針對母對象的實例,而是針對名稱空間(Module
類對象),其常量被搜索到未命名的實例被分配給他們。
沒錯。感謝這 - 幫助很多.. – user1541542
+1教學noobs'each_object'。但是我必須警告你在這裏展示的方法 - 它不適用於例如。參數化子類。 –