Ruby同一命名空间下跨类访问单例配置对象实例变量的方法
单实例配置对象的实例变量访问方案
当我们处理仅需实例化一次的类对象(例如Gem配置对象),且该配置类会调用多个需要访问其实例变量的类时,如何让这些类获取配置的实例变量?以下是两种可行的实现方案:
方案一:将Config对象实例作为参数传递
这种方案直接在初始化依赖类时,把Config的实例传递进去,让依赖类通过这个实例获取所需的变量。
# 将Config对象实例作为参数传递的示例 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
方案二:将Config对象存储为模块的类实例变量
这种方案把Config实例赋值给模块的类实例变量,依赖类可以直接通过模块访问这个配置实例,从而获取所需变量。
# 将Config对象存储为模块类实例变量的示例 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
内容的提问来源于stack exchange,提问作者TenJack
相关产品推荐
相关产品推荐

