The trouble with the other answers is all the methods return "self" so if you want to access a nested value...
final_value = Settings.new.method_1.method_2.method_3
You're just going to get the whole settings hash instead.
Try this instead...
class Settings
class SubSettings
def initialize(sub_setting)
@sub_setting = sub_setting
end
def method_missing(method, *arguments, &block)
if @sub_setting[method].is_a?(Hash)
SubSettings.new @sub_setting[method]
else
@sub_setting[method]
end
end
def answer
@sub_setting
end
end
def initialize
@settings = ConfigurationSettings
end
def method_missing(method, *arguments, &block)
SubSettings.new @settings[method]
end
end
ConfigurationSettings = {level1a: {level2a: {level3a: "hello", level3b: "goodbye"}, level2b: {level3b: "howdy"}}}
result = Settings.new.level1a.level2a.level3b
p result
=> "goodbye"
What this does is take the initial method and takes the associated sub-hash of the ConfigurationSettings hash and stored it into a new object of class SubSettings. It applies the next method and if the result is another sub-hash it iterates to create another SubSettings, etc. It only returns the actual result when it no longer sees hashes.