Module: ConfigMan::Parsers::JSON

Defined in:
lib/configman/parsers/json.rb

Constant Summary collapse

CONFIG_FILE_PATH =
File.join(Dir.pwd, '.config').freeze

Class Method Summary collapse

Class Method Details

.parse(file_path) ⇒ Object

Parse the .config file and return a hash of the configuration values

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
# File 'lib/configman/parsers/json.rb', line 12

def self.parse(file_path)
  raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)

  file_content = File.read(file_path)
  parsed_config = ::JSON.parse(file_content)

  raise ArgumentError, "Invalid JSON format in #{file_path}" unless parsed_config.is_a?(Hash)

  parsed_config
end

.update(key, new_value) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/configman/parsers/json.rb', line 23

def self.update(key, new_value)
  existing_config = parse(CONFIG_FILE_PATH)
  existing_config[key] = new_value

  File.open(CONFIG_FILE_PATH, 'w') do |file|
    file.write(::JSON.pretty_generate(existing_config))
  end
end

.write(config_hash) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/configman/parsers/json.rb', line 32

def self.write(config_hash)
  # Access the loaded modules and expected keys from the main class
  loaded_modules = ConfigMan.used_modules
  expected_keys = ConfigMan.expected_keys

  # Use the utility method to sort the keys into their respective sections
  sorted_config = Utils.sort_into_sections(config_hash, expected_keys, loaded_modules)

  File.open(CONFIG_FILE_PATH, 'w') do |file|
    file.write(::JSON.pretty_generate(sorted_config))
  end
end