我可以创建一个透明地呈现方法和变量的类吗?

时间:2014-02-18 20:14:12

标签: ruby lazy-loading

我想用Ruby做一些配置文件。配置的某些元素名义上取决于其他元素,但不一定。

例如,在使用配置时,我想这样做:

require_relative "config" 
require_relative "overrides" 
dosomething_with(Config.libpath)

在“config”中,我想要类似的东西:

require 'ostruct'
Config = OpenStruct.new
Config.basepath = "/usr"
Config.libpath = lambda {Config.basepath + "/lib"}    # this is not quite what I want

在“覆盖”中,用户可能会覆盖Config.basepath,我希望Config.libpath获取自然值。但是用户可能覆盖Config.libpath到某个常量。

我希望能够只说出Config.libpath并获得计算值(如果它没有被覆盖)或定义的值(如果有)。

这是我用Ruby做的事吗?这似乎是我看到OpenStruct如何工作的自然延伸。

1 个答案:

答案 0 :(得分:2)

这个怎么样:

require 'ostruct'

Config = OpenStruct.new
Config.basepath = "/usr"

def Config.libpath
  # Suggested by Nathaniel himself
  @table[:libpath] || basepath + "/lib"

  # The next alternatives require def Config.libpath=(libpath) ...
  # instance_variable_defined?(:@libpath) ? @libpath : basepath + "/lib"
  # or 
  # @libpath || basepath + "/lib" , depending on your needings
end

# Needed only if @table[:libpath] is not used
# def Config.libpath=(libpath)
#   @libpath = libpath
# end

# Default basepath, default libpath
p Config.libpath #=> "/usr/lib"

# custom basepath, default libpath
Config.basepath = "/var"
p Config.libpath #=> "/var/lib"

# Custom libpath
Config.libpath = '/lib'
p Config.libpath #=> "/lib"