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 - Songify ex complete #443

Open
wants to merge 4 commits into
base: songify-ex
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
24 changes: 15 additions & 9 deletions lib/songify.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

module Songify
def self.create_db_connection(dbname)
PG.connect(host: 'localhost', dbname: dbname)
PG.connect(host: 'localhost', dbname: dbname, user: "ruby", password: "rubyRailsJS")
end

def self.clear_db(db)
db.exec <<-SQL
DELETE FROM albums;
DELETE FROM songs;
DELETE FROM genres;
DELETE FROM albumgenres CASCADE;
DELETE FROM genres CASCADE;
DELETE FROM songs CASCADE;
DELETE FROM albums CASCADE;
/* TODO: Clear rest of the tables (books, etc.) */
SQL
end
Expand All @@ -22,22 +23,27 @@ def self.create_tables(db)
);
CREATE TABLE songs(
id SERIAL PRIMARY KEY,
album_id integer REFERENCES genres (id),
album_id integer REFERENCES albums (id),
title VARCHAR
);
CREATE TABLE genres(
id SERIAL PRIMARY KEY,
name VARCHAR
);
/* TODO: Create song_genres table */
CREATE TABLE albumgenres(
id SERIAL PRIMARY KEY,
album_id integer REFERENCES albums (id),
genre_id integer REFERENCES genres (id)
);
SQL
end

def self.drop_tables(db)
db.exec <<-SQL
DROP TABLE albums;
DROP TABLE songs;
DROP TABLE genres;
DROP TABLE albumgenres CASCADE;
DROP TABLE albums CASCADE;
DROP TABLE songs CASCADE;
DROP TABLE genres CASCADE;
/* TODO: Drop song_genres table */
SQL
end
Expand Down
55 changes: 51 additions & 4 deletions lib/songify/album_repo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,50 @@ class AlbumRepo
def self.all(db)
# Other code should not have to deal with the PG:Result.
# Therefore, convert the results into a plain array.
db.exec("SELECT * FROM albums").to_a
r1 = db.exec("SELECT * FROM albums").to_a
q = <<-SQL
SELECT
ag.album_id,
g.name
FROM genres g
JOIN albumgenres ag
ON g.id = ag.genre_id
SQL

genres = db.exec(q).to_a
genres.each do |genre|
r1.each do |album|
if(album['id'] == genre['album_id'])
album['genres']||album['genres'] = []
album['genres'].push(genre['name'])
end
end
end
return r1
end

def self.find(db, album_id)
db.exec("SELECT * FROM albums WHERE id=$1", [album_id]).first
r1 = db.exec("SELECT * FROM albums WHERE id=$1", [album_id]).first

q = <<-SQL
SELECT
ag.album_id,
g.name
FROM genres g
JOIN albumgenres ag
ON g.id = ag.genre_id
WHERE ag.album_id=$1
SQL

r2 = db.exec(q, [album_id]).to_a
if(r2 != [])
r1['genres'] = []

r2.each do |genre|
r1['genres'].push(genre)
end
end
return r1
end

def self.save(db, album_data)
Expand All @@ -17,9 +56,17 @@ def self.save(db, album_data)
self.find(db, album_data['id'])
else
raise "title is required." if album_data['title'].nil? || album_data['title'] == ''
result = db.exec("INSERT INTO albums (title) VALUES ($1) RETURNING id", [album_data['title']])

result = db.exec("INSERT INTO albums (title) VALUES ($1) RETURNING *", [album_data['title']])
album_data['id'] = result.entries.first['id']
album_data

if album_data["genre_ids"]
album_data["genre_ids"].each do |genre_id|
db.exec("INSERT INTO albumgenres (album_id, genre_id) VALUES ($1, $2)", [album_data["id"], genre_id])
end

end
return album_data
end
end

Expand Down
16 changes: 13 additions & 3 deletions lib/songify/song_repo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,21 @@ def self.save(db, song_data)
album = AlbumRepo.find(db, song_data['album_id'])
raise "A valid album_id is required." if album.nil?

result = db.exec("INSERT INTO songs (title) VALUES ($1) RETURNING id", [song_data['title']])
result = db.exec("INSERT INTO songs (title, album_id) VALUES ($1, $2) RETURNING id", [song_data['title'], song_data['album_id']])
song_data['id'] = result.entries.first['id']
song_data
end
return song_data
end
def self.all_with_album(db)
r = db.exec <<-SQL
SELECT s.id,
s.title AS song_title,
a.title AS album_title
FROM songs s
JOIN albums a
on s.album_id = a.id
SQL
r.to_a
end

end
end
24 changes: 23 additions & 1 deletion server.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'sinatra'
require './lib/songify.rb'
require 'json'

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

Expand All @@ -10,22 +11,43 @@
get '/albums' do
db = Songify.create_db_connection('songify_dev')
@albums = Songify::AlbumRepo.all(db)
@genres = JSON.generate(Songify::GenreRepo.all(db))
erb :"albums/index"
end

post '/albums' do
db = Songify.create_db_connection('songify_dev')
album = Songify::AlbumRepo.save(db, {
'title' => params[:title]
'title' => params[:title],
'genre_ids' => params[:genres]
})
redirect to '/albums'
end


get '/songs' do
db = Songify.create_db_connection('songify_dev')
@songs = Songify::SongRepo.all_with_album(db)
erb :"songs/index"
end

get '/songs/add' do
db = Songify.create_db_connection('songify_dev')
@albums = Songify::AlbumRepo.all(db)
@genres = JSON.generate(Songify::GenreRepo.all(db))

erb :"songs/add"
end
post '/songs/add' do
db = Songify.create_db_connection('songify_dev')
data = {}
data["title"] = params["title"]
data["album_id"] = params["album"]
Songify::SongRepo.save(db, data)

redirect to '/songs'
end


get '/genres' do
db = Songify.create_db_connection('songify_dev')
Expand Down
3 changes: 1 addition & 2 deletions spec/repos/album_repo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ def album_count
}
end

xit "can be assigned genres" do
it "can be assigned genres" do
gid_1 = Songify::GenreRepo.save(db, { 'name' => 'rock' })
gid_2 = Songify::GenreRepo.save(db, { 'name' => 'avant-garde' })
gid_3 = Songify::GenreRepo.save(db, { 'name' => 'jazz' })

album = repo.save(db, { 'title' => 'Suspicious Activity?',
'genre_ids' => [gid_1['id'], gid_2['id'], gid_3['id']] })
album = repo.find(db, album['id'])
Expand Down
1 change: 1 addition & 0 deletions spec/repos/song_repo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def song_count

it "updates songs" do
song1 = repo.save(db, { 'album_id' => @album_id, 'title' => "The Ally" })
song1['id']
song2 = repo.save(db, { 'id' => song1['id'], 'title' => "Alicia" })
expect(song2['id']).to eq(song1['id'])
expect(song2['title']).to eq "Alicia"
Expand Down
45 changes: 42 additions & 3 deletions views/albums/index.erb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,46 @@

<form action="/albums" method="post">
<h3>New Album</h3>
<label>Album Title:</label>
<input name="title" type="text" />
<button>Create Album</button>
<label for='title'>Album Title:</label>
<input name="title" type="text" /><br><br>
<div class="genre-add" style="margin-top:3px">
<select class="genres" name="genres[]"></select><span style="margin-left:3px" class="remove btn btn-warning glyphicon glyphicon-minus">Remove Genre</span>
</div>
<span id="add">Add a genre</span><br><br>

<button class="btn btn-default">Create Album</button>
</form>
<script>
genres = <%= @genres %>
$(document).ready(function(){

selectcount = 1
option = $("<option>")
option.text('-- Please select a Genre --')
$("select.genres").append(option)
$.each(genres, function(k,g){
option = $("<option>")
option.val(g.id)
option.text(g.name)
$("select.genres").append(option)
})
$('#add').addClass('btn')
$('#add').addClass('glyphicon')
$('#add').addClass('glyphicon-plus')
$('#add').addClass('btn-success')
$('#add').click(function(e){

element = $(e.currentTarget)
$('.genre-add').clone().insertBefore(element)
$('.remove').click(function(e){
console.log(e)
element = $(e.currentTarget)
$($(element).parent()).remove()

})

})


})
</script>