Created
January 2, 2016 15:12
-
-
Save ik5/a4e129bec69d6c4de5dc to your computer and use it in GitHub Desktop.
An example for dynamic configuration loading in ruby (using json)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"key1": "string", | |
"key2": true, | |
"key3": 10, | |
"nested": { | |
"nested_key1": [1] | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
conf = Conf.new('conf.json')
conf.get_key1 'default value'