Class: Song

Inherits:
Object
  • Object
show all
Defined in:
lib/top_100/song.rb

Constant Summary collapse

@@songs =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(song_hash) ⇒ Song

Returns a new instance of Song.



5
6
7
8
# File 'lib/top_100/song.rb', line 5

def initialize(song_hash)
  song_hash.each {|key, value| self.send("#{key}=", value)}
  @@songs << self
end

Instance Attribute Details

#artist_nameObject

Returns the value of attribute artist_name.



2
3
4
# File 'lib/top_100/song.rb', line 2

def artist_name
  @artist_name
end

#artist_urlObject

Returns the value of attribute artist_url.



2
3
4
# File 'lib/top_100/song.rb', line 2

def artist_url
  @artist_url
end

#nameObject

Returns the value of attribute name.



2
3
4
# File 'lib/top_100/song.rb', line 2

def name
  @name
end

#rankObject

Returns the value of attribute rank.



2
3
4
# File 'lib/top_100/song.rb', line 2

def rank
  @rank
end

#urlObject

Returns the value of attribute url.



2
3
4
# File 'lib/top_100/song.rb', line 2

def url
  @url
end

Class Method Details

.allObject

class methods



25
26
27
# File 'lib/top_100/song.rb', line 25

def self.all
  @@songs
end

.find_by_rank(rank) ⇒ Object



29
30
31
# File 'lib/top_100/song.rb', line 29

def self.find_by_rank(rank)
  song = Song.all.find {|song| song.rank == rank }
end

Instance Method Details

#slugObject

slug method used to help make query for spotify API request



11
12
13
# File 'lib/top_100/song.rb', line 11

def slug
  self.name.gsub(/\s+/, "%20").delete('^a-zA-Z0-9\%').downcase
end


15
16
17
18
19
20
21
# File 'lib/top_100/song.rb', line 15

def spotify_link
  response = open("https://api.spotify.com/v1/search?q=#{self.slug}&type=track").read
  json_info = JSON.parse(response)
  # songs share same track name, ensure that artist name includes the first artist to find a match.
  song_details = json_info["tracks"]["items"].find { |info| self.artist_name.downcase.include?(info["artists"][0]["name"].downcase) }
  song_details == nil ? nil : song_details["preview_url"]
end