class BookStore
BookStore
Class
Public Class Methods
new()
click to toggle source
Loading the Data into the books from file
# File lib/book_store.rb, line 7 def initialize @books = [] File.open(File.dirname(__FILE__) + '/books.txt').each do |line| book_name = line.split('|').first book_rating = line.split('|').last book = Book.new(book_name.intern, book_rating) @books << book end end
Public Instance Methods
book_add(name, rating)
click to toggle source
Add Book
to the file and also to the books
# File lib/book_store.rb, line 18 def book_add(name, rating) book = Book.new(name.intern, rating) @books << book File.open(File.dirname(__FILE__) + '/books.txt', 'a') do |line| line.puts book.name.to_s + '|' + book.rating + "\r" end puts 'Book added successfully!' end
book_delete(name)
click to toggle source
Delete Book
to the file and also to the books
# File lib/book_store.rb, line 28 def book_delete(name) file_lines = '' IO.readlines(File.dirname(__FILE__) + '/books.txt').each do |line| file_lines += line unless line.split('|').first == name end File.open(File.dirname(__FILE__) + '/books.txt', 'w') do |file| file.puts file_lines end initialize puts 'Book deleted successfully!' end
book_display()
click to toggle source
Displays the content
# File lib/book_store.rb, line 41 def book_display @books.each do |book| puts "Book: #{book.name.to_s}, Rating: #{book.rating}" end end
book_exists(name)
click to toggle source
Method to check if book exists
# File lib/book_store.rb, line 61 def book_exists(name) @books.each do |book| return true if book.name == name end false end
book_search(search)
click to toggle source
Search for the content in the list of the books
# File lib/book_store.rb, line 48 def book_search(search) flag = false @books.each do |book| book2 = book.name.to_s.downcase if book2.include? search puts "Book: #{book.name.to_s}, Rating: #{book.rating}" flag = true end end puts flag ? '' : 'No Book found matching your criteria' end