1
0
mirror of https://github.com/danbee/mpd-client synced 2025-03-04 08:39:09 +00:00

More class work.

This commit is contained in:
Dan Barber 2013-09-02 22:48:34 +01:00
parent 68042e18e0
commit 8d75b39e95
4 changed files with 50 additions and 40 deletions

View File

@ -10,14 +10,18 @@ class Album
@year = first_song.date @year = first_song.date
end end
def self.by_artist(artist)
MPDConnection.mpd.albums(artist).map { |album| Album.new(album) }
end
def <=>(album) def <=>(album)
year <=> album.year year <=> album.year
end end
def self.all
MPDConnection.mpd.albums.sort.map { |artist| Album.new(album) }
end
def self.by_artist(artist)
MPDConnection.mpd.albums(artist).map { |album| Album.new(album) }
end
def attributes def attributes
{ title: @title, { title: @title,
genre: @genre, genre: @genre,

21
models/artist.rb Normal file
View File

@ -0,0 +1,21 @@
require './models/mpd_connection'
class Artist
attr_accessor :name
def initialize(name)
@name = name
end
def <=>(artist)
name <=> artist.name
end
def self.all
MPDConnection.mpd.artists.sort.map { |artist| Artist.new(artist) }
end
def attributes
{ name: @name }
end
end

View File

@ -6,6 +6,7 @@ require 'json'
require 'cgi' require 'cgi'
require './models/album' require './models/album'
require './models/artist'
class MPDClient < Sinatra::Base class MPDClient < Sinatra::Base
register Sinatra::Namespace register Sinatra::Namespace
@ -13,52 +14,25 @@ class MPDClient < Sinatra::Base
namespace '/api' do namespace '/api' do
get '/albums' do get '/albums' do
JSON mpd.albums JSON Album.all.map(&:attributes)
end end
get '/artists/:artist' do get '/artists/:artist' do
JSON get_albums_by_artist(CGI.unescape(params[:artist])) JSON Album.by_artist(CGI.unescape(params[:artist])).sort.map(&:attributes)
end end
get '/albums/:album' do #get '/albums/:album' do
JSON get_songs_by_album(CGI.unescape(params[:album])) #JSON get_songs_by_album(CGI.unescape(params[:album]))
end #end
get '/artists/:artist/:album' do #get '/artists/:artist/:album' do
JSON get_songs_by_album(CGI.unescape(params[:album])) #JSON get_songs_by_album(CGI.unescape(params[:album]))
end #end
get '/artists' do get '/artists' do
JSON mpd.artists JSON Artist.all.map(&:attributes)
end end
end end
private
def get_albums_by_artist(artist)
mpd.albums(artist).map { |album| album_info(album) }.sort { |a, b| a[:year] <=> b[:year] }
end
def get_songs_by_album(album)
mpd.search(:album, album).map { |song| song_info(song) }
end
def song_info(song)
{ disc: song.disc,
track: song.track,
title: song.title }
end
def album_info(album)
first_song = mpd.search(:album, album).first
{ title: first_song.album,
genre: first_song.genre,
year: first_song.date }
end
def mpd
MPDConnection.mpd
end
end end

View File

@ -0,0 +1,11 @@
require 'spec_helper'
describe Artist do
let(:artist) { Artist.new('Alice Cooper') }
it 'has attributes' do
expect(artist.name).to eq('Alice Cooper')
end
end