Skip to content

Commit

Permalink
Using 'method_missing' to reduce the code base
Browse files Browse the repository at this point in the history
  • Loading branch information
oleander committed Mar 8, 2011
1 parent d5602e5 commit f4fda8e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 21 deletions.
42 changes: 25 additions & 17 deletions lib/spotify.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,38 @@
class Spotify
attr_writer :url

def songs
return @songs if @songs

@songs = []; content["tracks"].each do |song|
song = SpotifyContainer::Song.new(song)
@songs << song if song.valid?
end
def initialize
@methods = {
:artists => {
:selector => :artists,
:class => SpotifyContainer::Artist
},
:songs => {
:selector => :tracks,
:class => SpotifyContainer::Song
}
}

@songs
@cache = {}
end

def artists
return @artists if @artists

@artists = []; content["artists"].each do |artist|
artist = SpotifyContainer::Artist.new(artist)
@artists << artist if artist.valid?
end

@artists
def method_missing(method, *args, &block)
@methods.keys.include?(method) ? scrape(method.to_sym) : super(method, *args, &block)
end

private

def scrape(type)
return @cache[type] if @cache[type]

@cache[type] = []; content[@methods[type][:selector].to_s].each do |item|
item = @methods[type][:class].new(item)
@cache[type] << @cache[type] if item.valid?
end

@cache[type]
end

def content
@content ||= JSON.parse(download)
end
Expand Down
8 changes: 4 additions & 4 deletions spec/spotify_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

it "should contain the right amounts of songs" do
set_up(100, true)
@spotify.should have(100).songs
@spotify.songs.count.should eq(100)
end

it "should call SpotifyContainer::Song with the right arguments" do
Expand All @@ -40,7 +40,7 @@

it "should not have any songs if nothing is valid" do
set_up(100, false)
@spotify.should have(0).songs
@spotify.songs.count.should eq(0)
end
end

Expand All @@ -56,7 +56,7 @@
end

it "should contain the right amounts of songs" do
@spotify.should have(100).artists
@spotify.artists.count.should eq(100)
end

it "should call SpotifyContainer::Artist with the right arguments" do
Expand All @@ -77,7 +77,7 @@

it "should not have any songs if nothing is valid" do
set_up(100, false, SpotifyContainer::Artist)
@spotify.should have(0).artists
@spotify.artists.count.should eq(0)
end
end

Expand Down

0 comments on commit f4fda8e

Please sign in to comment.