-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathoptions.rb
More file actions
119 lines (94 loc) · 2.72 KB
/
options.rb
File metadata and controls
119 lines (94 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
require 'ostruct'
module Msg91ruby
class Options < OpenStruct
include Enumerable
def empty?
marshal_dump.empty?
end
def add_source!(source)
# handle yaml file paths
source = (Sources::YAMLSource.new(source)) if source.is_a?(String)
@config_sources ||= []
@config_sources << source
end
def reload_env!
return self if ENV.nil? || ENV.empty?
conf = Hash.new
ENV.each do |key, value|
next unless key.to_s.index(Msg91ruby.const_name) == 0
hash = value
key.to_s.split('.').reverse.each do |element|
hash = {element => hash}
end
DeepMerge.deep_merge!(hash, conf, :preserve_unmergeables => false)
end
merge!(conf[Msg91ruby.const_name] || {})
end
alias :load_env! :reload_env!
# look through all our sources and rebuild the configuration
def reload!
conf = {}
@config_sources.each do |source|
source_conf = source.load
if conf.empty?
conf = source_conf
else
DeepMerge.deep_merge!(source_conf, conf, :preserve_unmergeables => false)
end
end
# swap out the contents of the OStruct with a hash (need to recursively convert)
marshal_load(__convert(conf).marshal_dump)
reload_env! if Msg91ruby.use_env
return self
end
alias :load! :reload!
def reload_from_files(*files)
Msg91ruby.load_and_set_settings(files)
reload!
end
def to_hash
result = {}
marshal_dump.each do |k, v|
result[k] = v.instance_of?(Msg91ruby::Options) ? v.to_hash : v
end
result
end
def each(*args, &block)
marshal_dump.each(*args, &block)
end
def to_json(*args)
require "json" unless defined?(JSON)
to_hash.to_json(*args)
end
def merge!(hash)
current = to_hash
DeepMerge.deep_merge!(hash.dup, current)
marshal_load(__convert(current).marshal_dump)
self
end
# An alternative mechanism for property access.
# This let's you do foo['bar'] along with foo.bar.
def [](param)
send("#{param}")
end
def []=(param, value)
send("#{param}=", value)
end
protected
# Recursively converts Hashes to Options (including Hashes inside Arrays)
def __convert(h) #:nodoc:
s = self.class.new
h.each do |k, v|
k = k.to_s if !k.respond_to?(:to_sym) && k.respond_to?(:to_s)
s.new_ostruct_member(k)
if v.is_a?(Hash)
v = v["type"] == "hash" ? v["contents"] : __convert(v)
elsif v.is_a?(Array)
v = v.collect { |e| e.instance_of?(Hash) ? __convert(e) : e }
end
s.send("#{k}=".to_sym, v)
end
s
end
end
end