문제

I'd like to do some config-file work with Ruby. Some elements of the config nominally depend on other elements, but not necessarily.

For example, when using the config, I'd like to do this:

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

In "config", I want something like:

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

In "overrides", the user might override Config.basepath, and I'd like Config.libpath to take the natural value. But the user might also override Config.libpath to some constant.

I'd like to be able to just say Config.libpath and either get the calculated value (if it hasn't been overridden) or the defined value (if it has).

Is this something I'd do with Ruby? It seems like a natural extension of how I've seen OpenStruct work.

도움이 되었습니까?

해결책

What about this:

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"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top