Class: Koz::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/koz/config.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Config

Returns a new instance of Config.



17
18
19
20
21
# File 'lib/koz/config.rb', line 17

def initialize path
  @path = path
  @config = YAML.load_file(path)
  @handler = -> (keys, new_value, old_value) {  }
end

Class Method Details

.connect_file(path) ⇒ Object



5
6
7
# File 'lib/koz/config.rb', line 5

def self.connect_file path
  new(path)
end

Instance Method Details

#delete(element, at:) ⇒ Object

delete an element at array [key]



87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/koz/config.rb', line 87

def delete element, at:
  case at
  when String
    if @config.key? at
      @config[at]
    else
      @config.dig(*at.split(/[\/.]/))
    end
  when Array
    @config.dig(*at)
  end.delete element
  save_config
end

#get(key, *rest) ⇒ Object Also known as: []



39
40
41
42
# File 'lib/koz/config.rb', line 39

def get key, *rest
  # keys = key.split('/')
  @config.dig(key, *rest)
end

#handle(&blk) ⇒ Object



23
24
25
# File 'lib/koz/config.rb', line 23

def handle &blk
  @handler = blk
end

#insert(element, at:) ⇒ Object

insert an element to a array [key]



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/koz/config.rb', line 72

def insert element, at:
  case at
  when String
    if @config.key? at
      @config[at]
    else
      @config.dig(*at.split(/[\/.]/))
    end
  when Array
    @config.dig(*at)
  end.push element
  save_config
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/koz/config.rb', line 13

def key? key
  @config.key? key
end

#keysObject



9
10
11
# File 'lib/koz/config.rb', line 9

def keys
  @config.keys
end

#reloadObject



27
28
29
# File 'lib/koz/config.rb', line 27

def reload
  @config = YAML.load_file(@path)
end

#safe_getObject



67
68
69
# File 'lib/koz/config.rb', line 67

def safe_get(*)
  YAML.load get(*).to_yaml
end

#save_configObject



35
36
37
# File 'lib/koz/config.rb', line 35

def save_config
  File.write(@path, @config.to_yaml)
end

#set(*keys, new_value, yaml: false) ⇒ Object Also known as: []=



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/koz/config.rb', line 44

def set *keys, new_value, yaml: false
  return false if keys.empty?
  # keys = keys.map{_1.split("/")}.flatten
  if yaml
    new_value = YAML.load(value)
  end

  key = keys.last
  if keys.size > 1
    container = @config.dig(*keys[..-2])
  else
    container = @config
  end
  old_value = container[key]
  container[key] = JSON.parse(new_value.to_json)
  @handler.call(keys, new_value, old_value)
  save_config
end

#to_yamlObject



31
32
33
# File 'lib/koz/config.rb', line 31

def to_yaml
  @config.to_yaml
end

#yaml_setObject



63
64
65
# File 'lib/koz/config.rb', line 63

def yaml_set(*)
  set(*, yaml: true)
end