You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.5 KiB
62 lines
1.5 KiB
require 'yaml'
|
|
require 'date'
|
|
require_relative '../student'
|
|
require_relative 'persistence_strategy'
|
|
|
|
class YAMLPersistenceStrategy
|
|
include PersistenceStrategy
|
|
|
|
def load(filename)
|
|
if File.exist?(filename)
|
|
begin
|
|
data = YAML.load_file(filename)
|
|
data.map { |student_hash| hash_to_student(student_hash) }
|
|
rescue StandardError => e
|
|
warn "Ошибка при загрузке YAML: #{e.message}"
|
|
[]
|
|
end
|
|
else
|
|
[]
|
|
end
|
|
end
|
|
|
|
def save(filename, students)
|
|
data = students.map { |student| student_to_hash(student) }
|
|
File.open(filename, 'w') do |file|
|
|
file.write(data.to_yaml)
|
|
end
|
|
rescue IOError => e
|
|
warn "Ошибка при записи в YAML: #{e.message}"
|
|
end
|
|
|
|
private
|
|
|
|
def student_to_hash(student)
|
|
{
|
|
'id' => student.id,
|
|
'git' => student.git,
|
|
'surname' => student.surname,
|
|
'name' => student.name,
|
|
'patronymic' => student.patronymic,
|
|
'birth_date' => student.birth_date.to_s,
|
|
'phone' => student.phone,
|
|
'telegram' => student.telegram,
|
|
'email' => student.email
|
|
}
|
|
end
|
|
|
|
def hash_to_student(hash)
|
|
Student.new(
|
|
id: hash['id'],
|
|
git: hash['git'],
|
|
surname: hash['surname'],
|
|
name: hash['name'],
|
|
patronymic: hash['patronymic'],
|
|
birth_date: Date.parse(hash['birth_date']),
|
|
phone: hash['phone'],
|
|
telegram: hash['telegram'],
|
|
email: hash['email']
|
|
)
|
|
end
|
|
end
|