Let's say I am working on a problem where a class object will only be instantiated once, such as a Gem configuration object. The configuration class calls many classes that use the configuration class object's instance variables.
How do you access the configuration object instance variables in these other classes? Here are some example implementations (passing the config object as self versus storing the config object as a class instance variable on the Module) that hopefully help clarify:
# This example passes the Config object as self
module NumberTally
class Config
attr_reader :to_tally
def initialize
@to_tally = [1,2,3,4,5]
perform
end
private
def perform
validate_to_tally
output_to_tally
end
def validate_to_tally
ValidateToTally.new(self).call
end
def output_to_tally
OutputToTally.new(self).call
end
end
class ValidateToTally
attr_reader :to_tally
def initialize(config)
@to_tally = config.to_tally
end
def call
raise TypeError if to_tally.any?{|num| num.class != Integer }
end
end
class OutputToTally
attr_reader :to_tally
def initialize(config)
@to_tally = config.to_tally
end
def call
to_tally.each do |num|
puts num
end
end
end
end
#use Class instance variable in the Module
module NumberTally
class << self
attr_accessor :config
end
class Config
attr_reader :to_tally
def initialize
@to_tally = [1,2,3,4,5]
NumberTally.config = self
perform
end
private
def perform
validate_to_tally
output_to_tally
end
def validate_to_tally
ValidateToTally.new.call
end
def output_to_tally
OutputToTally.new.call
end
end
class ValidateToTally
def call
raise TypeError if to_tally.any?{|num| num.class != Integer }
end
private
def to_tally
@to_tally ||= NumberTally.config.to_tally
end
end
class OutputToTally
def call
to_tally.each do |num|
puts num
end
end
private
def to_tally
@to_tally ||= NumberTally.config.to_tally
end
end
end