Class: Defmastership::ConfigPreserver

Inherits:
Object
  • Object
show all
Defined in:
lib/defmastership/config_preserver.rb

Overview

The configuration can be modified by Mofifiers (e.g. ChangeRef). The configuration file need to include these modifications without:

- saving default values
- removing empty line
- removing comments

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ ConfigPreserver

Returns a new instance of ConfigPreserver.



14
15
16
# File 'lib/defmastership/config_preserver.rb', line 14

def initialize(filename)
  @filename = filename
end

Instance Method Details

#configHash

Get the yaml config from configuration file

Returns:

  • (Hash)

    the configuration



21
22
23
24
# File 'lib/defmastership/config_preserver.rb', line 21

def config
  # idiomatic way to perform a deep clone of a hash
  Marshal.load(Marshal.dump(YAML.load_file(@filename)))
end

#save(new_config) ⇒ Hash

Save the updated configuration taking into account blank lines and comments

Returns:

  • (Hash)

    the configuration



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/defmastership/config_preserver.rb', line 29

def save(new_config)
  # we don't wan't to add new configuration items from default values
  new_config_content = config.merge_no_new(new_config).to_yaml.split("\n")

  # Put in there place the emty lines and comments
  File.open(@filename, 'r').each_line(chomp: true).with_index do |line, line_num|
    if /\A\s*(\#.*)?\z/.match?(line)
      new_config_content.insert(line_num, line)
    elsif line =~ /\A\s*[^\s].+?(\s*\#.*)\z/
      new_config_content[line_num] += Regexp.last_match(1)
    end
  end

  File.write(@filename, "#{new_config_content.join("\n")}\n")
end