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



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

def self.all
  @@songs
end

.play(rank) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/top_100/song.rb', line 34

def self.play(rank)
  song = Song.all.find {|song| song.rank == rank }
  if song.nil?
    puts "You've entered an invalid chart name."
  else
    song.url = song.spotify_link
    #check if song has a valid url, copyright issues with certain songs
    if !!song.url
      puts "Playing song..."
      `open #{song.url}`
    else
      puts "Sorry, that artist does not have their song on Spotify."
    end
  end
end

Instance Method Details

#displayObject



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

def display
  puts "##{self.rank}: #{self.name} by #{self.artist_name}."
  puts "--------------------------------"
end

#slugObject

slug method used to help make query for spotify API request



16
17
18
# File 'lib/top_100/song.rb', line 16

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


21
22
23
24
25
26
# File 'lib/top_100/song.rb', line 21

def spotify_link
  response = open("https://api.spotify.com/v1/search?q=#{self.slug}&type=track").read
  json_info = JSON.parse(response)
  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