From 2e884a8e309bb3418d0bf496ddcefcd9d9ed8703 Mon Sep 17 00:00:00 2001 From: Dan Barber Date: Wed, 4 Sep 2013 15:13:23 +0100 Subject: [PATCH] Refactor models using Struct. --- models/album.rb | 19 ++++++------------- models/artist.rb | 14 ++------------ mpd_client.rb | 6 +++--- 3 files changed, 11 insertions(+), 28 deletions(-) diff --git a/models/album.rb b/models/album.rb index b1d80f4..d53dd10 100644 --- a/models/album.rb +++ b/models/album.rb @@ -1,13 +1,12 @@ require './models/mpd_connection' -class Album - attr_accessor :title, :genre, :year +class Album < Struct.new(:title, :genre, :year) def initialize(album) first_song = MPDConnection.mpd.search(:album, album).first - @title = first_song.album - @genre = first_song.genre - @year = first_song.date + self.title = first_song.album + self.genre = first_song.genre + self.year = first_song.date end def <=>(album) @@ -15,16 +14,10 @@ class Album end def self.all - MPDConnection.mpd.albums.sort.map { |artist| Album.new(album) } + MPDConnection.mpd.albums.sort.map { |artist| self.new(album) } end def self.by_artist(artist) - MPDConnection.mpd.albums(artist).map { |album| Album.new(album) } - end - - def attributes - { title: @title, - genre: @genre, - year: @year } + MPDConnection.mpd.albums(artist).map { |album| self.new(album) } end end diff --git a/models/artist.rb b/models/artist.rb index dcf564e..0a365d4 100644 --- a/models/artist.rb +++ b/models/artist.rb @@ -1,17 +1,7 @@ require './models/mpd_connection' -class Artist - attr_accessor :name - - def initialize(name) - @name = name - end - +class Artist < Struct.new(:name) def self.all - MPDConnection.mpd.artists.sort.map { |artist| Artist.new(artist) } - end - - def attributes - { name: @name } + MPDConnection.mpd.artists.sort.map { |artist| self.new(artist) } end end diff --git a/mpd_client.rb b/mpd_client.rb index bced13f..2e51764 100644 --- a/mpd_client.rb +++ b/mpd_client.rb @@ -14,11 +14,11 @@ class MPDClient < Sinatra::Base namespace '/api' do get '/albums' do - JSON Album.all.map(&:attributes) + JSON Album.all.map(&:to_h) end 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 #get '/albums/:album' do @@ -30,7 +30,7 @@ class MPDClient < Sinatra::Base #end get '/artists' do - JSON Artist.all.map(&:attributes) + JSON Artist.all.map(&:to_h) end end