Class: BookStore

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/book_store.rb

Overview

BookStore Class

Instance Method Summary collapse

Constructor Details

#initializeBookStore

Loading the Data into the books from file



7
8
9
10
11
12
13
14
15
# 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

Instance Method Details

#book_add(name, rating) ⇒ Object

Add Book to the file and also to the books



18
19
20
21
22
23
24
25
# 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) ⇒ Object

Delete Book to the file and also to the books



28
29
30
31
32
33
34
35
36
37
38
# 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_displayObject

Displays the content



41
42
43
44
45
# 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) ⇒ Object

Method to check if book exists



61
62
63
64
65
66
# 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) ⇒ Object

Search for the content in the list of the books



48
49
50
51
52
53
54
55
56
57
58
# 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