-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbook_methods.rb
100 lines (80 loc) · 2.48 KB
/
book_methods.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
93
94
95
96
97
98
99
100
require './book'
require './label'
require 'json'
class BookMethods
attr_accessor :books, :labels
def initialize
@books = []
@labels = []
end
def list_all_books
puts 'List of books:'
if @books.empty?
puts 'No books found.'
else
@books.each { |book| puts "#{book.author}'s book, published in #{book.publish_date}" }
end
end
def list_all_labels
puts 'List of labels:'
if labels.empty?
puts 'No labels found'
else
labels.each { |label_item| puts "#{label_item.title},#{label_item.color}" }
end
end
def add_a_book
puts 'Enter the book author:'
author = gets.chomp
puts 'Enter book publisher:'
publisher = gets.chomp
puts 'Enter book publication Year:'
publish_date = gets.chomp.to_i
archived = Time.now.year - publish_date > 10
puts 'Choose book cover state[Good/Bad]:'
cover_state = gets.chomp
puts 'Choose a suitable title for the library:'
title = gets.chomp
puts 'Choose a suitable color for the library:'
color = gets.chomp
book_item = Book.new(author, publish_date, archived, publisher, cover_state)
@books.push(book_item)
new_label_item = Label.new(title, color)
new_label_item.add_item(book_item)
@labels.push(new_label_item)
puts "New book by #{book_item.author} published by #{book_item.publisher} added successfully"
end
def save_book
book_to_hash = books.map do |hash|
{
author: hash.author,
cover_state: hash.cover_state,
publish_date: hash.publish_date,
archived: hash.archived,
publisher: hash.publisher,
label: { title: hash.label.title, color: hash.label.color }
}
end
json = JSON.pretty_generate(book_to_hash)
File.write('./database/book.json', json)
end
def load_book
return [] unless File.exist?('./database/book.json')
book_data = JSON.parse(File.read('./database/book.json'))
@books.clear
book_data.each do |book|
author = book['author']
publish_date = book['publish_date']
archived = book['archived']
publisher = book['publisher']
cover_state = book['cover_state']
label_title = book['label']['title']
label_color = book['label']['color']
book_item = Book.new(author, publish_date, archived, publisher, cover_state)
@books.push(book_item)
new_label_item = Label.new(label_title, label_color)
new_label_item.add_item(book_item)
@labels.push(new_label_item)
end
end
end