-
Notifications
You must be signed in to change notification settings - Fork 0
/
book_database.rb
113 lines (98 loc) · 2.71 KB
/
book_database.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
101
102
103
104
105
106
107
108
109
110
111
112
113
# This class mimics a database that stores book information.
# Data is saved to a JSON file.
#
# The class provides methods to retrieve `all` records,
# `find` a record by id, `add` a new record, and `update`
# the information of an existing record.
#
# This approach is NOT a good idea for real systems,
# but it is good enough the purposes of this workshop.
#
class BookDatabase
# This class represents a single book
class Book
attr_accessor :id, :title, :author, :year
def initialize(id: 0, title: "", author: "", year: Time.now.year)
@id = id
@title = title
@author = author
@year = year
end
def self.new_from_hash(hash)
Book.new(id: hash["id"], title: hash["title"], author: hash["author"], year: hash["year"])
end
# see: https://stackoverflow.com/a/40642530/446681
def as_json(options={})
{ id: @id, title: @title, author: @author, year: @year }
end
# see: https://stackoverflow.com/a/40642530/446681
def to_json(*options)
as_json(*options).to_json(*options)
end
def to_s
"id: #{@id}, title: #{@title}, author: #{@author}"
end
end
#
# Returns all the records in the underlying JSON file
def self.all
text = "[]"
if File.exists?("books.json")
text = File.read("books.json")
end
data = JSON.parse(text)
books = data.map { |hash| Book.new_from_hash(hash) }
books
end
#
# Finds one record by id
def self.find(id)
book = all.find { |book| book.id == id.to_i }
end
#
# Returns a new empty book (but it does not save it)
def self.create_new
Book.new
end
#
# Adds a record to the underlying JSON file
def self.add(title, author, year)
# Calculate the id for the new book...
new_id = get_new_book_id()
# ...and save the new book
new_book = Book.new(id: new_id, title: title, author: author, year: year)
books = all
books << new_book
File.write("books.json", JSON.pretty_generate(books))
new_id
end
#
# Updates the information of a given record in the JSON file
def self.update(id, title, author, year)
# Spin through all the books...
books = all
books.each do |book|
# ...if this record has the id that was provided
if book.id == id.to_i
# ... update it
book.title = title
book.author = author
book.year = year
# ... write the changes to disk
File.write("books.json", JSON.pretty_generate(books))
return true
end
end
return false
end
#
# Calculates the id for a new book
def self.get_new_book_id
books = all
if books.count == 0
return 1
end
latest_book = books.max_by { |book| book.id }
return latest_book.id + 1
end
end