generated from microverseinc/readme-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanipulate_data.rb
92 lines (85 loc) · 3.05 KB
/
manipulate_data.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
require_relative './lib/book'
# this module will help preserve the data when the app is closed
module PreserveData
def preserve_books
book_objects = []
@books.each do |book|
book_obj = { title: book.title, author: book.author }
book_objects.push(book_obj)
end
File.write('./data/books.json', JSON.generate(book_objects))
end
def preserve_persons
persons_objects = []
@persons.each do |person|
person_obj = if person.instance_of?(::Student)
{ class_name: person.class.name,
name: person.name, id: person.id,
age: person.age,
parent_permission: person.parent_permission,
classroom: person.classroom }
else
{ class_name: person.class.name,
name: person.name, id: person.id,
age: person.age,
parent_permission: person.parent_permission,
specialization: person.specialization }
end
persons_objects.push(person_obj)
end
File.write('./data/persons.json', JSON.generate(persons_objects))
end
def preserve_rentals
rentals_objects = []
@rentals.each do |rental|
rental_obj = {
date: rental.date,
person: { name: rental.person.name },
book: { title: rental.book.title }
}
rentals_objects.push(rental_obj)
end
File.write('./data/rentals.json', JSON.generate(rentals_objects))
end
end
# this module will help laod the data when the app is open the first time
module LoadData
def load_books
if File.exist?('./data/books.json') && File.size('./data/books.json').positive?
file_data = JSON.parse(File.read('./data/books.json'))
file_data.each do |book|
new_book = Book.new(book['title'], book['author'])
@books << new_book
end
else
''
end
end
def load_persons
if File.exist?('./data/persons.json') && File.size('./data/persons.json').positive?
file_data = JSON.parse(File.read('./data/persons.json'))
file_data.each do |person|
new_person = if person['class_name'] == 'Student'
Student.new(person['age'], person['classroom'], person['name'], person['parent_permission'])
else
Teacher.new(person['age'], person['specialization'], person['name'], person['parent_permission'])
end
@persons.push(new_person)
end
else
''
end
end
def load_rentals
if File.exist?('./data/rentals.json') && File.size('./data/rentals.json').positive?
file_data = JSON.parse(File.read('./data/rentals.json'))
file_data.each do |rental|
person_index = @persons.index { |person| person.name.eql?(rental['person']['name']) }
book_index = @books.index { |book| book.title.eql?(rental['book']['title']) }
@rentals << Rental.new(@persons[person_index], @books[book_index], rental['date'])
end
else
''
end
end
end