如何在 Ruby 中跨同一命名空间内的不同类访问 Class 对象的实例变量

问题描述 投票:0回答:0

假设我正在处理一个类对象只会被实例化一次的问题,例如 Gem 配置对象。配置类调用许多使用配置类对象的实例变量的类。

你如何访问这些其他类中的配置对象实例变量?以下是一些示例实现(将配置对象作为 self 传递与将配置对象作为类实例变量存储在模块上),希望有助于澄清:

# 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

ruby instance-variables
© www.soinside.com 2019 - 2024. All rights reserved.