-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbook.rb
More file actions
39 lines (33 loc) · 820 Bytes
/
book.rb
File metadata and controls
39 lines (33 loc) · 820 Bytes
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
require 'json'
class Book
attr_accessor :title, :author, :rentals
def initialize(title, author)
@title = title
@author = author
@rentals = []
end
def add_rental(rental)
@rentals << rental
rental
end
def self.save_books_to_json(books)
books_data = books.map(&:to_hash)
File.write('books.json', JSON.pretty_generate(books_data))
end
def self.load_books_from_json
books_data = JSON.parse(File.read('books.json'))
books_data.map { |data| Book.new(data['title'], data['author']) }
rescue StandardError
[]
end
def to_hash
{
'title' => @title,
'author' => @author,
'rentals' => @rentals.map { |rental| { 'date' => rental.date } }
}
end
def self.find_by_title(books, title)
books.find { |book| book.title == title }
end
end