Skip to content

Instantly share code, notes, and snippets.

@ik5
Created January 2, 2016 15:12
Show Gist options
  • Save ik5/a4e129bec69d6c4de5dc to your computer and use it in GitHub Desktop.
Save ik5/a4e129bec69d6c4de5dc to your computer and use it in GitHub Desktop.
An example for dynamic configuration loading in ruby (using json)
{
"key1": "string",
"key2": true,
"key3": 10,
"nested": {
"nested_key1": [1]
}
}
require 'json'
class Conf
def initialize(file, opts={symbolize_names: true})
@file = file
@options = opts
load_file
end
def load_file
@json = JSON.parse(open(@file).read, @options)
end
def get(key, default='')
@json[key] || default
end
def method_missing(method_sym, *arguments)
case method_sym.to_s
when /^get_nested(.*?)$/
# todo
when /^get_(.*?)$/
key = $1
key = key.to_sym if @options[:symbolize_names] == true
self.get(key,(arguments.first || ''))
else
super
end
end
def respond_to?(method, include_private = false)
if method.to_s =~ /^get_.*?$/
true
else
super
end
end
end
@ik5
Copy link
Author

ik5 commented Jan 2, 2016

usage:
conf = Conf.new('conf.json')
conf.get_key1 'default value'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment