Class: MusicCompare::Compare

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

Instance Method Summary collapse

Constructor Details

#initialize(client_id: ENV['CLIENT_ID'], client_secret: ENV['CLIENT_SECRET']) ⇒ Compare

Returns a new instance of Compare.



12
13
14
# File 'lib/music_compare.rb', line 12

def initialize(client_id: ENV['CLIENT_ID'], client_secret: ENV['CLIENT_SECRET'])
  RSpotify.authenticate(client_id, client_secret)
end

Instance Method Details

#compare(playlist1, playlist2, dir_path: '') ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/music_compare.rb', line 16

def compare(playlist1, playlist2, dir_path: '')
  fetch_playlists!([playlist1, playlist2], dir_path: dir_path)
  file1 = CSV.read(playlist_path(playlist1, dir_path: @dir_path))
  file2 = CSV.read(playlist_path(playlist2, dir_path: @dir_path))
  matches_arr = file1 & file2
  CSV.open("#{dir_path}matches.csv", 'w') do |matches|
    matches_arr.each { |line| matches << line }
  end
  rm_dir(dir_path)
end

#fetch_playlists!(playlists, dir_path: '') ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/music_compare.rb', line 27

def fetch_playlists!(playlists, dir_path: '')
  create_dir(dir_path)
  playlists.each do |playlist|
    response = make_request(playlist_request(playlist))
    CSV.open(playlist_path(playlist, dir_path: @dir_path), 'a') do |playlist_file|
      loop do
        response['items'].each do |track|
          playlist_file << [
            track['track']['name'],
            track['track']['artists'].map { |artist| artist['name'] }.join(' ')
          ]
        end
        break if response['next'].nil?

        response = make_request(response['next'])
      end
    end
  end
end