Class: JSON_storage_strategy

Inherits:
Data_storage_strategy show all
Defined in:
lib/models/data_storage_strategy/JSON_storage_strategy.rb

Instance Method Summary collapse

Instance Method Details

#read(file_path) ⇒ Object

read from json file



7
8
9
10
11
12
13
# File 'lib/models/data_storage_strategy/JSON_storage_strategy.rb', line 7

def read(file_path)
    return [] unless File.exist?(file_path)
    data = JSON.parse(File.read(file_path), symbolize_names: true) rescue []
    data.map do |data|
        Student.new(**data)
    end
end

#write(file_path, students) ⇒ Object

read to json file



16
17
18
19
# File 'lib/models/data_storage_strategy/JSON_storage_strategy.rb', line 16

def write(file_path, students)
    data = students.map { |student| student.to_h }
    File.write(file_path, JSON.pretty_generate(data))
end