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

Refactor models using Struct.

This commit is contained in:
Dan Barber 2013-09-04 15:13:23 +01:00
parent 9258b2749e
commit 2e884a8e30
3 changed files with 11 additions and 28 deletions

View File

@ -1,13 +1,12 @@
require './models/mpd_connection' require './models/mpd_connection'
class Album class Album < Struct.new(:title, :genre, :year)
attr_accessor :title, :genre, :year
def initialize(album) def initialize(album)
first_song = MPDConnection.mpd.search(:album, album).first first_song = MPDConnection.mpd.search(:album, album).first
@title = first_song.album self.title = first_song.album
@genre = first_song.genre self.genre = first_song.genre
@year = first_song.date self.year = first_song.date
end end
def <=>(album) def <=>(album)
@ -15,16 +14,10 @@ class Album
end end
def self.all def self.all
MPDConnection.mpd.albums.sort.map { |artist| Album.new(album) } MPDConnection.mpd.albums.sort.map { |artist| self.new(album) }
end end
def self.by_artist(artist) def self.by_artist(artist)
MPDConnection.mpd.albums(artist).map { |album| Album.new(album) } MPDConnection.mpd.albums(artist).map { |album| self.new(album) }
end
def attributes
{ title: @title,
genre: @genre,
year: @year }
end end
end end

View File

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

View File

@ -14,11 +14,11 @@ class MPDClient < Sinatra::Base
namespace '/api' do namespace '/api' do
get '/albums' do get '/albums' do
JSON Album.all.map(&:attributes) JSON Album.all.map(&:to_h)
end end
get '/artists/:artist' do get '/artists/:artist' do
JSON Album.by_artist(CGI.unescape(params[:artist])).sort.map(&:attributes) JSON Album.by_artist(CGI.unescape(params[:artist])).sort.map(&:to_h)
end end
#get '/albums/:album' do #get '/albums/:album' do
@ -30,7 +30,7 @@ class MPDClient < Sinatra::Base
#end #end
get '/artists' do get '/artists' do
JSON Artist.all.map(&:attributes) JSON Artist.all.map(&:to_h)
end end
end end