這是一個很好的做法嗎?存儲由常量訪問的對象。有很多方法可以存儲要由其他類訪問的對象進行處理。除了* @@ class_variables之外,使用常量來存儲指向集合的哈希對象是我最近開始做的事情。如果有的話,那麼親/ /這是什麼?對OOP來說並不是什麼新鮮事,但是任何洞察力都將是不好的做法。這是一個好習慣嗎?存儲由常量訪問的對象...
#!/usr/bin/env ruby
OUTSIDE_STATE = true
NAMES = {:objects => []}
module CheckSelf
module ClassMethods
def self.inherited(child)
::NAMES[:objects] << child
end
def select_and_make_calls
_selected = NAMES[:objects].select {|child|
child.purpose()
}.each {|child|
# _child = child.new(child)
child.new(child).call_out
}
end
end
module InstanceMethods
def call_out
puts "FIRING OFF THE CALLS #{self.class}"
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
class Parent
def initialize(name)
@name = name
end
include CheckSelf
# The inherited class must be defined in the *
# Body of the class.
def self.inherited(child)
NAMES[:objects] << child
end
end
class ObjectOne < Parent
def self.purpose
OUTSIDE_STATE
end
end
class ObjectTwo < Parent
def self.purpose
true
end
end
Parent.select_and_make_calls
您可能想看看Ruby如何使用#object_id和ObjectSpace類來完成其中的一些工作:http://corelib.rubyonrails.org/classes/ObjectSpace.html#M001614 – joelparkerhenderson 2012-04-06 15:43:48