lib/modules/storage.rb in codebreaker-Bulatkin-0.1.0 vs lib/modules/storage.rb in codebreaker-Bulatkin-0.1.1
- old
+ new
@@ -1,24 +1,37 @@
# frozen_string_literal: true
module Codebreaker
- PATH = './db'
- FILE_NAME = 'data.yml'
module Storage
- class << self
- def save(results)
- FileUtils.mkdir_p(PATH) unless Dir.exist?(PATH)
- data = load << results
- File.open(File.join(Dir.pwd, PATH, FILE_NAME), 'a+') { |file| file.write(data.to_yaml) }
- end
+ PATH = 'db'
+ FILE_NAME = 'data.yml'
- def load
- YAML.safe_load(File.join(Dir.pwd, PATH, FILE_NAME))
- []
- end
+ def save(results)
+ FileUtils.mkdir_p(PATH) unless Dir.exist?(PATH)
+ data = load_database << results
+ write_data(data)
+ end
- def sort_player
- load_database.sort_by { |game| [game[:difficulty], game[:attempts_used], game[:hints_used]] }
- end
+ def load_database
+ YAML.safe_load(File.read(file_path))
+ end
+
+ def sort_player
+ create_storage unless File.exist?(file_path)
+ load_database.sort_by { |game| [game[:difficulty], game[:attempts_used], game[:hints_used]] }
+ end
+
+ private
+
+ def file_path
+ File.join(Dir.pwd, PATH, FILE_NAME)
+ end
+
+ def create_storage
+ write_data([])
+ end
+
+ def write_data(data)
+ File.open(file_path, 'w') { |file| file.write(data.to_yaml) }
end
end
end