Class: Spotify::Collection

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data:, total:) ⇒ Collection

Returns a new instance of Collection.



61
62
63
64
# File 'lib/spotify/collection.rb', line 61

def initialize(data:, total:)
  @data = data
  @total = total
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



3
4
5
# File 'lib/spotify/collection.rb', line 3

def data
  @data
end

#totalObject (readonly)

Returns the value of attribute total.



3
4
5
# File 'lib/spotify/collection.rb', line 3

def total
  @total
end

Class Method Details

.from_response(response, type:, key: nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/spotify/collection.rb', line 5

def self.from_response(response, type:, key: nil)
  body = response.body

  if key.is_a?(String)
    data = body[key].map { |attrs| type.new(attrs) }
  else
    data = body.map { |attrs| type.new(attrs) }
  end

  new(
    data: data,
    total: data.count,
  )
end

.from_search_response(response) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/spotify/collection.rb', line 20

def self.from_search_response(response)
  body = response.body

  data = []

  puts body["tracks"].count

  if body["tracks"] && body["tracks"]["items"]
    data.concat(body["tracks"]["items"].map { |attrs| Track.new(attrs) })
  end

  if body["artists"] && body["artists"]["items"]
    data.concat(body["artists"]["items"].map { |attrs| Artist.new(attrs) })
  end

  if body["albums"] && body["albums"]["items"]
    data.concat(body["albums"]["items"].map { |attrs| Album.new(attrs) })
  end

  if body["playlists"] && body["playlists"]["items"]
    data.concat(body["playlists"]["items"].map { |attrs| Playlist.new(attrs) })
  end

  if body["shows"] && body["shows"]["items"]
    data.concat(body["shows"]["items"].map { |attrs| Show.new(attrs) })
  end

  if body["episodes"] && body["episodes"]["items"]
    data.concat(body["episodes"]["items"].map { |attrs| Episode.new(attrs) })
  end

  if body["audiobooks"] && body["audiobooks"]["items"]
    data.concat(body["audiobooks"]["items"].map { |attrs| Audiobook.new(attrs) })
  end

  new(
    data: data,
    total: data.count,
  )
end

Instance Method Details

#countObject



78
79
80
# File 'lib/spotify/collection.rb', line 78

def count
  data.count
end

#each(&block) ⇒ Object



66
67
68
# File 'lib/spotify/collection.rb', line 66

def each(&block)
  data.each(&block)
end

#firstObject



70
71
72
# File 'lib/spotify/collection.rb', line 70

def first
  data.first
end

#lastObject



74
75
76
# File 'lib/spotify/collection.rb', line 74

def last
  data.last
end