如何跨相同模块的类访问类实例变量?

时间:2011-12-15 22:23:37

标签: ruby class module scope instance-variables

我需要从模块的另一个类中访问配置变量。

在test.rb中,如何从client.rb获取配置值? @config给了我一个未初始化的var。它在同一个模块中,但是不同的类。

创建配置的新实例是最好的选择吗?如果是这样,我如何通过run.rb传递参数?

或者,我只是构建这个错误或者我应该使用attr_accessor吗?

client.rb

module Cli
  class Client

    def initialize(config_file)
      @config_file = config_file
      @debug = false
    end

    def config
      @config ||= Config.new(@config_file)
    end

    def startitup
      Cli::Easy.test
    end
 end
end

config.rb

module Cli
  class Config
    def initialize(config_path)
      @config_path = config_path
      @config = {}
      load
    end

    def load
      begin
        @config = YAML.load_file(@config_path)
      rescue
        nil
      end
    end
  end
end

test.rb

module Cli
  class Easy
    def self.test
      puts @config
    end
  end
end

run.rb

client = Cli::Client.new("path/to/my/config.yaml")
client.startitup

1 个答案:

答案 0 :(得分:1)

@config是一个实例变量,如果你想从外面获取它,你需要提供访问器,并给Easy类自我对象。

client.rb:

attr_reader :config
#...
def startitup
  Cli::Easy.test(self)
end

test.rb

def self.test(klass)
  puts klass.config
end

如果您使用@@ config,那么您可以使用class_variable_get来访问此变量而不提供自身对象。

class Lol
  @@lold = 0
  def initialize(a)
    @@lold = a
  end
end
x = Lol.new(4)
puts Lol.class_variable_get("@@lold")

我建议你阅读元编程红宝石书。

相关问题