Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Greg Mikeska - Library plus #432

Open
wants to merge 5 commits into
base: library-plus
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion lib/library_plus.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,28 @@

module Library
def self.create_db_connection(dbname)
PG.connect(host: 'localhost', dbname: dbname)
cstring = {
host: "localhost",
dbname: dbname,
user: "ruby",
password: "rubyRailsJS"
}
PG.connect(cstring)
end

def self.clear_db(db)
db.exec <<-SQL
DELETE FROM users;
/* TODO: Clear rest of the tables (books, etc.) */
SQL
db.exec <<-SQL
DELETE FROM books;
/* TODO: Clear rest of the tables (books, etc.) */
SQL
db.exec <<-SQL
DELETE FROM checkouts;
/* TODO: Clear rest of the tables (books, etc.) */
SQL
end

def self.create_tables(db)
Expand All @@ -20,15 +34,37 @@ def self.create_tables(db)
);
/* TODO: Create rest of the tables (books, etc.) */
SQL
db.exec <<-SQL
CREATE TABLE books(
id SERIAL PRIMARY KEY,
title VARCHAR,
author VARCHAR
);
SQL
db.exec <<-SQL
CREATE TABLE checkouts(
id SERIAL PRIMARY KEY,
book_id INTEGER,
user_id INTEGER,
checkout_date date,
due_date date,
return_date date
);
SQL
end

def self.drop_tables(db)
db.exec <<-SQL
DROP TABLE users;
/* TODO: Drop rest of the tables (books, etc.) */
SQL
db.exec <<-SQL
DROP TABLE books;
/* TODO: Drop rest of the tables (books, etc.) */
SQL
end
end

require_relative 'library_plus/book_repo'
require_relative 'library_plus/user_repo'
require_relative 'library_plus/checkout_repo'
60 changes: 60 additions & 0 deletions lib/library_plus/book_repo.rb
Original file line number Diff line number Diff line change
@@ -1 +1,61 @@
module Library
class BookRepo

def self.all(db)
# Other code should not have to deal with the PG:Result.
# Therefore, convert the results into a plain array.
b = db.exec("SELECT * FROM books").to_a
checkouts = Library::CheckoutRepo.all_by_book(db)
b.each do |book|
book['available'] = true
id = book['id']
if (checkouts[id])
book['checkouts'] = checkouts[id]
book['checkouts'].each do |checkout|
book['available'] = false if !checkout['return_date']
end
end
end
return b
end

def self.find(db, book_data)
book = db.exec("SELECT * FROM books WHERE id = #{book_data}").to_a[0]
checkouts = Library::CheckoutRepo.find_with_user(db, 'book_id' => book['id']) # should return array
book['available'] = true

if (checkouts)
book['checkouts'] = checkouts
book['checkouts'].each do |checkout|
book['available'] = false if !checkout['return_date']
end
end

return book
end

def self.save(db, book_data)
if book_data["id"]
s = ""
if(book_data["title"])
s+="title = '"+book_data["title"]+"'"
end
if(book_data["title"] && book_data["author"])
s+=","
end
if(book_data["author"])
s+="author = '"+book_data["author"]+"'"
end
db.exec("UPDATE books SET #{s} WHERE id = #{book_data['id']} returning *").to_a[0]
else
db.exec("INSERT INTO books (title, author) VALUES ('#{book_data["title"]}', '#{book_data["author"]}') returning *").to_a[0]
end
end

def self.destroy(db, book_data)
r = db.exec("DELETE FROM books WHERE id = #{book_data}")
return r.cmd_status()
end
end
end
# TODO
52 changes: 46 additions & 6 deletions lib/library_plus/user_repo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,62 @@ def self.all(db)
# Therefore, convert the results into a plain array.
db.exec("SELECT * FROM users").to_a
end
def self.all_with_checkouts(db)
# Other code should not have to deal with the PG:Result.
# Therefore, convert the results into a plain array.
u = db.exec("SELECT * FROM users").to_a
checkouts = Library::CheckoutRepo.all_by_user(db)
u.each do |user|
id = user['id']
user['checkouts.outstanding'] = []
if (checkouts[id])
user['checkouts'] = checkouts[id]
checkouts[id].each do |checkout|
unless(checkout['return_date'])
user['checkouts.outstanding'].push(checkout)
end
end
end
end
return u
end

def self.find(db, user_data)
# TODO: Insert SQL statement
def self.find_with_checkouts(db, user_data)
user = db.exec("SELECT * FROM users WHERE id = #{user_data}").to_a[0]


checkouts = Library::CheckoutRepo.all_by_user(db)
id = user['id']
user['checkouts.outstanding'] = []
if (checkouts[id])
user['checkouts'] = checkouts[id]

checkouts[id].each do |checkout|
unless(checkout['return_date'])
user['checkouts.outstanding'].push(checkout)
end
end
end
return user
end

def self.find(db, user_data)
db.exec("SELECT * FROM users WHERE id = #{user_data}").to_a[0]


end
def self.save(db, user_data)
if user_data['id']
# TODO: Update SQL statement
db.exec("UPDATE users SET name = '#{user_data['name']}' WHERE id = #{user_data['id']} returning *").to_a[0]
else
# TODO: Insert SQL statement
db.exec("INSERT INTO users (name) VALUES ('#{user_data['name']}') returning *").to_a[0]
end
end

def self.destroy(db, user_data)
# TODO: Delete SQL statement
end
r = db.exec("DELETE FROM users WHERE id = #{user_data}")
return r.cmd_status()

end
end
end
72 changes: 72 additions & 0 deletions server.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,80 @@
require 'sinatra'
require './lib/library_plus'
require 'sinatra/reloader'
require 'json'

# set :bind, '0.0.0.0' # This is needed for Vagrant

get '/' do
erb :index
end

get '/users' do
db = Library.create_db_connection('library_dev')
@users = Library::UserRepo.all_with_checkouts(db)
erb :"users/index"
end
get '/users/:id' do
db = Library.create_db_connection('library_dev')
@user = Library::UserRepo.find_with_checkouts(db, params[:id])
erb :"users/info"
end
post '/users' do
db = Library.create_db_connection('library_dev')
@u = Library::UserRepo.save(db, "name" => params["user_name"])
redirect to("/users")
end

get '/users/:id/delete' do
db = Library.create_db_connection('library_dev')
r = Library::UserRepo.destroy(db, params["id"])
if(r.split().last == "1")
@u = "User ##{params["id"]} has been deleted successfully!"
else
@u = "Error deleting user ##{params["id"]}."
end
erb :"users/delete"
end

get '/books' do
db = Library.create_db_connection('library_dev')
@books = Library::BookRepo.all(db)
@users = JSON.generate(Library::UserRepo.all(db)) # Querying this to populate checkout list.
erb :"books/index"
end

post '/books' do
db = Library.create_db_connection('library_dev')
@b = Library::BookRepo.save(db, {"title" => params["book_title"], "author" => params["book_author"]})
redirect to("/books")
end

get '/books/:id' do
db = Library.create_db_connection('library_dev')
@book = Library::BookRepo.find(db, params['id'])
erb :"books/info"
end

get '/books/:id/delete' do
db = Library.create_db_connection('library_dev')
r = Library::BookRepo.destroy(db, params["id"])
if(r.split().last == "1")
@u = "Book ##{params["id"]} has been deleted successfully!"
else
@u = "Error deleting book ##{params["id"]}."
end
erb :"books/delete"
end

get '/books/:id/checkout' do
db = Library.create_db_connection('library_dev')
@users = Library::UserRepo.all(db)
@book = Library::BookRepo.find(db, params['id'])
erb :"books/checkout"
end

post '/books/:id/checkout' do
db = Library.create_db_connection('library_dev')
Library.CheckoutRepo.save(db, checkout_data)
redirect to("/books")
end
21 changes: 11 additions & 10 deletions spec/repos/user_repo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,39 +27,40 @@ def user_count(db)
it "creates users" do
expect(user_count(db)).to eq 0

user = Library::UserRepo.save(db, :name => "Alice")
user = Library::UserRepo.save(db, { 'name' => "Alice" })
expect(user['id']).to_not be_nil
expect(user['name']).to eq "Alice"


# Check for persistence
expect(user_count(db)).to eq 1

user = db.exec("SELECT * FROM users")[0]
expect(user['name']).to eq "Alice"
end

xit "finds users" do
user = Library::UserRepo.save(db, :name => "Alice")
it "finds users" do
user = Library::UserRepo.save(db, { 'name' => "Alice" })
retrieved_user = Library::UserRepo.find(db, user['id'])
expect(retrieved_user['name']).to eq "Alice"
end

xit "updates users" do
user1 = Library::UserRepo.save(db, :name => "Alice")
user2 = Library::UserRepo.save(db, :name => "Alicia")
it "updates users" do
user1 = Library::UserRepo.save(db, { 'name' => "Alice" })
user2 = Library::UserRepo.save(db, { 'id' => user1['id'], 'name' => "Alicia" })
expect(user2['id']).to eq(user1['id'])
expect(user2['name']).to eq "Alicia"

# Check for persistence
user3 = Library::UserRepo.find(user1['id'])
user3 = Library::UserRepo.find(db, user1['id'])
expect(user3['name']).to eq "Alicia"
end

xit "destroys users" do
user = Library::UserRepo.save(db, :name => "Alice")
it "destroys users" do
user = Library::UserRepo.save(db, { 'name' => "Alice" })
expect(user_count(db)).to eq 1

Library::UserRepo.destroy(db, user['id'])
expect(user_count(db)).to eq 0
end
end
end
3 changes: 3 additions & 0 deletions views/index.erb
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
<h1>The Library Plus System</h1>

<p>Welcome to your freedom!</p>

<a href="/users">Manage Users</a><br>
<a href="/books">Manage Books</a>