Class: PiggyOptionsPersistence

Inherits:
Object
  • Object
show all
Defined in:
lib/piggy-core/options_persistence.rb

Overview

Store PiggyOptions into (or load from) configuration files. File format will be Yaml. File location will be system specific:

"#{WinShell.instance.path_for_special_folder("LOCALAPPDATA")}/piggy"

Instance Method Summary collapse

Constructor Details

#initializePiggyOptionsPersistence

Returns a new instance of PiggyOptionsPersistence.



14
15
16
17
18
19
20
21
# File 'lib/piggy-core/options_persistence.rb', line 14

def initialize
  super 
  shell = WinShell.instance
  local_app_data_path = shell.path_for_special_folder("LOCALAPPDATA")
  piggy_app_data_path = local_app_data_path + "#{File::SEPARATOR}" + 'piggy'
  Dir.mkdir(piggy_app_data_path) unless File.directory?(piggy_app_data_path)
  @optionsFile = piggy_app_data_path + "#{File::SEPARATOR}" + 'options.yaml'
end

Instance Method Details

#load_yamlObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/piggy-core/options_persistence.rb', line 23

def load_yaml
  return PiggyOptions.new unless File.exists?(@optionsFile)
  begin
    config = File.open(@optionsFile) { |io| YAML.load(io) }
    if config.class == Array
      options = config.detect{ |entry| entry.class == PiggyOptions }
    else 
      options = config
    end
    options.initialize_nils_with_default
  rescue StandardError => ex
    puts('Configuration error, options.yaml ignored: ' + ex.message)
    options = PiggyOptions.new
  end
  return options
end

#save_yaml(options) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/piggy-core/options_persistence.rb', line 40

def save_yaml(options)
  begin
    if File.exists?(@optionsFile)
      File.rename(@optionsFile, "#{@optionsFile}.bak")
    end
    File.open(@optionsFile, 'w') { |out|
      YAML.dump(options, out)
    }
    puts "Options saved to #{@optionsFile}"
  rescue StandardError => ex
    puts "Options could not be saved to #{@optionsFile}: " + ex.message
  end
end