2

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.

2
  • OpenStruct uses method_missing for its magic, you might as well have a look at that if you don't have an issue with performance Commented Feb 18, 2014 at 20:17
  • be careful with OpenStruct as it consumes memory very quickly. I have experienced it myself but See this Question Commented Feb 18, 2014 at 21:46

1 Answer 1

2

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" 
Sign up to request clarification or add additional context in comments.

2 Comments

Just what I was looking for! I peeked at the source of OpenStruct, and it seems to work to use @table[:libpath] instead of @libpath, and then I don't need to define the libpath= method.
Oh yes, I looked it too once in the past, you reminded me it uses @table, I update the answer =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.