Total Complexity | 2 |
Total Lines | 47 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | require 'dotenv' |
||
5 | class Loader |
||
6 | attr_accessor :config |
||
7 | |||
8 | def initialize(config) |
||
9 | @config = config |
||
10 | Dotenv.load |
||
11 | config_env |
||
12 | end |
||
13 | |||
14 | def config_env |
||
15 | ENV.keys.grep(/^LITA_/i) do |key| |
||
16 | val = ENV[key] |
||
17 | slugs = key.split('__') |
||
18 | # Convert value types |
||
19 | if slugs.length==2 |
||
20 | type = slugs[1].downcase |
||
21 | if type=='typesym' |
||
22 | val = val.to_sym |
||
23 | elsif type == 'typebool' |
||
24 | val = val.downcase == 'true' ? true : false |
||
25 | elsif type == 'typeint' && val =~ /^\s*[0-9]+\s*$/ |
||
26 | val = val.to_i |
||
27 | elsif type == 'typejson' |
||
28 | val = MultiJson.decode val |
||
29 | elsif type == 'typejsonsym' |
||
30 | val = MultiJson.decode val, symbolize_keys: true |
||
31 | end |
||
32 | end |
||
33 | # Convert path |
||
34 | path = slugs[0].split('_') |
||
35 | path.shift # Remove LITA prefix |
||
36 | path.each_with_index do |part, i| |
||
37 | if part =~ /[a-z]/ |
||
38 | path[i] = part.gsub(/([A-Z])/, '_\1') |
||
39 | end |
||
40 | path[i].downcase! |
||
41 | end |
||
42 | if path.length == 2 |
||
43 | @config.send(path[0]).send("#{path[1]}=",val) |
||
44 | elsif path.length == 3 |
||
45 | @config.send(path[0]).send(path[1]).send("#{path[2]}=",val) |
||
46 | else |
||
47 | raise "Config path length #{path.length} not supported for #{path.join('.')}." |
||
48 | end |
||
49 | end |
||
50 | end |
||
51 | end |
||
52 | end |
||
53 |