Is this good practice? Storing objects accessed by a constant. There are plenty of ways to store objects to be accessed by other classes for processing. Using constants instead as means to store hash objects that point to collections is something I recently started doing besides * @@class_variables. What would be the pro’s / con’s to this if there are any? Not really new to OOP but any insight what would be bad practice would be appreciated.
#!/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
I recommend against using constants to store changing data. Using constants not only tells the interpreter that your data won’t change, it also tells other programmers that read your code. If you need somewhere to store data over time, use a
@@class_variable, and@instance_variableor a$globalinstead.This is not so much an OOP convention as a ruby convention.