Class: Credman::Set

Inherits:
Base
  • Object
show all
Defined in:
lib/credman/set.rb

Instance Method Summary collapse

Methods inherited from Base

#config_has_keys?, #configs, #decript, #initialize, #key_for, #pastel, #print_key_and_value, #rewrite_config_for

Constructor Details

This class inherits a constructor from Credman::Base

Instance Method Details

#deep_set!(obj, keys, value) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/credman/set.rb', line 34

def deep_set!(obj, keys, value)
  key = keys.first
  if keys.length == 1
    obj[key] = value
  else
    obj[key] = {} unless obj[key]
    deep_set!(obj[key], keys.slice(1..-1), value)
  end
end

#normalize_new_value(new_value) ⇒ Object



44
45
46
47
48
# File 'lib/credman/set.rb', line 44

def normalize_new_value(new_value)
  return if new_value.in?(%w[nil null])

  new_value
end

#perform(key, new_value) ⇒ Object



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
# File 'lib/credman/set.rb', line 3

def perform(key, new_value)
  key_with_path = key.split(".").map(&:to_sym)
  new_value = normalize_new_value(new_value)
  abort pastel.red("Invalid key") if key.blank?

  configs.each do |env, config|
    puts pastel.green("#{env}:")
    update_config = true

    if config_has_keys?(config, key_with_path)
      previous_value = configs[env].dig(*key_with_path)
      if previous_value == new_value
        value = "NOT CHANGED. The value already the same: #{new_value.inspect}"
        update_config = false
      else
        value = "CHANGED: #{new_value.inspect}; previous value: #{previous_value.inspect}"
      end
    else
      value = "ADDED: #{new_value}"
    end

    print_key_and_value(key, value)

    if update_config
      updated_config = config.dup
      deep_set!(updated_config, key_with_path, new_value)
      rewrite_config_for(env, updated_config)
    end
  end
end