You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 03:07:39