Class: Ace::Support::Config::Molecules::YamlLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/ace/support/config/molecules/yaml_loader.rb

Overview

YAML file loading with error handling

Class Method Summary collapse

Class Method Details

.load_and_merge(*filepaths, merge_strategy: :replace) ⇒ Models::Config

Load and merge multiple YAML files

Parameters:

  • filepaths (Array<String>)

    Paths to YAML files

  • merge_strategy (Symbol) (defaults to: :replace)

    How to merge arrays (:replace, :concat, :union)

Returns:



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/ace/support/config/molecules/yaml_loader.rb', line 59

def self.load_and_merge(*filepaths, merge_strategy: :replace)
  configs = filepaths.flatten.map do |filepath|
    load_file_safe(filepath)
  end

  return Models::Config.new({}, source: "empty") if configs.empty?

  # Merge all configs using the specified strategy
  merged_data = configs.map(&:data).reduce({}) do |result, data|
    Atoms::DeepMerger.merge(result, data, array_strategy: merge_strategy)
  end

  Models::Config.new(
    merged_data,
    source: "merged(#{filepaths.join(", ")})",
    merge_strategy: merge_strategy
  )
end

.load_file(filepath) ⇒ Models::Config

Load YAML from file

Parameters:

  • filepath (String)

    Path to YAML file

Returns:

Raises:



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/ace/support/config/molecules/yaml_loader.rb', line 16

def self.load_file(filepath)
  unless File.exist?(filepath)
    raise ConfigNotFoundError, "Configuration file not found: #{filepath}"
  end

  content = File.read(filepath)
  data = Atoms::YamlParser.parse(content)

  Models::Config.new(data, source: filepath)
rescue IOError, SystemCallError => e
  raise ConfigNotFoundError, "Failed to read file #{filepath}: #{e.message}"
end

.load_file_safe(filepath) ⇒ Models::Config

Load YAML from file, return empty config if not found

Parameters:

  • filepath (String)

    Path to YAML file

Returns:



32
33
34
35
36
# File 'lib/ace/support/config/molecules/yaml_loader.rb', line 32

def self.load_file_safe(filepath)
  load_file(filepath)
rescue ConfigNotFoundError
  Models::Config.new({}, source: "#{filepath} (not found)")
end

.save_file(config, filepath) ⇒ Object

Save configuration to YAML file

Parameters:

  • config (Models::Config, Hash)

    Configuration to save

  • filepath (String)

    Path to save to

Raises:

  • (IOError)

    if save fails



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ace/support/config/molecules/yaml_loader.rb', line 42

def self.save_file(config, filepath)
  data = config.is_a?(Models::Config) ? config.data : config
  yaml_content = Atoms::YamlParser.dump(data)

  # Create directory if it doesn't exist
  dir = File.dirname(filepath)
  FileUtils.mkdir_p(dir) unless File.directory?(dir)

  File.write(filepath, yaml_content)
rescue IOError, SystemCallError => e
  raise IOError, "Failed to save file #{filepath}: #{e.message}"
end