require 'json' require 'date' require_relative '../student' require_relative 'persistence_strategy' class JSONPersistenceStrategy include PersistenceStrategy def load(filename) if File.exist?(filename) file_content = File.read(filename) begin data = JSON.parse(file_content) data.map { |student_hash| hash_to_student(student_hash) } rescue JSON::ParserError => e warn "Ошибка парсинга JSON: #{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(JSON.pretty_generate(data)) end rescue IOError => e warn "Ошибка при записи в файл: #{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