这是好习惯吗?存储常量访问的对象。有很多方法可以存储对象以供其他类访问以进行处理。除了 * @@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