Class: RSpotify::Base

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Base

Returns a new instance of Base.


118
119
120
121
122
123
124
# File 'lib/rspotify/base.rb', line 118

def initialize(options = {})
  @external_urls = options['external_urls']
  @href          = options['href']
  @id            = options['id']
  @type          = options['type']
  @uri           = options['uri']
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object

Used internally to retrieve an object's instance variable. If instance variable equals nil, calls #complete! on object and retrieve it again.

Examples:

user.id #=> "wizzler"

track = artist.tracks.first
track.instance_variable_get("@popularity") #=> nil
track.popularity #=> 62
track.instance_variable_get("@popularity") #=> 62

190
191
192
193
194
195
196
197
198
199
# File 'lib/rspotify/base.rb', line 190

def method_missing(method_name, *args)
  attr = "@#{method_name}"
  return super if method_name.match(/[\?!]$/) || !instance_variable_defined?(attr)

  attr_value = instance_variable_get attr
  return attr_value if !attr_value.nil? || @id.nil?

  complete!
  instance_variable_get attr
end

Instance Attribute Details

#external_urlsHash

Known external URLs for object

Returns:

  • (Hash)

    the current value of external_urls


8
9
10
# File 'lib/rspotify/base.rb', line 8

def external_urls
  @external_urls
end

#hrefString

A link to the Web API endpoint

Returns:

  • (String)

    the current value of href


8
9
10
# File 'lib/rspotify/base.rb', line 8

def href
  @href
end

#idString

The Spotify ID for the object

Returns:

  • (String)

    the current value of id


8
9
10
# File 'lib/rspotify/base.rb', line 8

def id
  @id
end

#typeString

The object type (artist, album, etc.)

Returns:

  • (String)

    the current value of type


8
9
10
# File 'lib/rspotify/base.rb', line 8

def type
  @type
end

#uriString

The Spotify URI for the object

Returns:

  • (String)

    the current value of uri


8
9
10
# File 'lib/rspotify/base.rb', line 8

def uri
  @uri
end

Class Method Details

.find(ids, type, market: nil) ⇒ Album, ...

Returns RSpotify object(s) with id(s) and type provided

Examples:

user = RSpotify::Base.find('wizzler', 'user')
user.class #=> RSpotify::User
user.id    #=> "wizzler"

ids = %w(2UzMpPKPhbcC8RbsmuURAZ 7Jzsc04YpkRwB1zeyM39wE)
tracks = RSpotify::Base.find(ids, 'track')
tracks.class       #=> Array
tracks.first.class #=> RSpotify::Track

Parameters:

Returns:


26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rspotify/base.rb', line 26

def self.find(ids, type, market: nil)
  case ids
  when Array
    if type == 'user'
      warn 'Spotify API does not support finding several users simultaneously'
      return false
    end
    find_many(ids, type, market: market)
  when String
    id = ids
    find_one(id, type, market: market)
  end
end

.search(query, types, limit: 20, offset: 0, market: nil) ⇒ Array<Album>, ...

Returns array of RSpotify objects matching the query, ordered by popularity. It's also possible to find the total number of search results for the query

Examples:

artists = RSpotify::Base.search('Arctic', 'artist')
albums  = RSpotify::Base.search('AM', 'album', limit: 10, market: 'US')
mixed   = RSpotify::Base.search('Arctic', 'artist, album, track')
albums  = RSpotify::Base.search('AM', 'album', market: { from: user })

RSpotify::Base.search('Arctic', 'album,artist,playlist').total #=> 2142

Parameters:

  • query (String)

    The search query's keywords. For details access here and look for the q parameter description.

  • types (String)

    Valid types are: album, artist, track and playlist. Separate multiple types with commas.

  • limit (Integer) (defaults to: 20)

    Maximum number of objects to return. Maximum: 50. Default: 20.

  • offset (Integer) (defaults to: 0)

    The index of the first object to return. Use with limit to get the next set of objects. Default: 0.

  • market (String, Hash) (defaults to: nil)

    Optional. An ISO 3166-1 alpha-2 country code or the hash { from: user }, where user is a RSpotify user authenticated using OAuth with scope user-read-private. This will take the user's country as the market value. (Playlist results are not affected by the market parameter.) For details access here and look for the market parameter description.

Returns:


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/rspotify/base.rb', line 91

def self.search(query, types, limit: 20, offset: 0, market: nil)
  query = CGI.escape query
  types.gsub!(/\s+/, '')

  url = "search?q=#{query}&type=#{types}"\
        "&limit=#{limit}&offset=#{offset}"

  response = if market.is_a? Hash
    url << '&market=from_token'
    User.oauth_get(market[:from].id, url)
  else
    url << "&market=#{market}" if market
    RSpotify.get(url)
  end

  return response if RSpotify.raw_response

  types = types.split(',')
  result = types.flat_map do |type|
    type_class = RSpotify.const_get(type.capitalize)
    response["#{type}s"]['items'].map { |i| type_class.new i }
  end

  insert_total(result, types, response)
  result
end

Instance Method Details

#complete!Object

Note:

It is seldom necessary to use this method explicitly, since RSpotify takes care of it automatically when needed (see #method_missing)

When an object is obtained undirectly, Spotify usually returns a simplified version of it. This method updates it into a full object, with all attributes filled.

Examples:

track = artist.tracks.first
track.instance_variable_get("@popularity") #=> nil
track.complete!
track.instance_variable_get("@popularity") #=> 62

176
177
178
# File 'lib/rspotify/base.rb', line 176

def complete!
  initialize RSpotify.get("#{@type}s/#{@id}")
end

#embed(options = {}) ⇒ Object

Generate an embed code for an album, artist or track. For full documentation on widgets/embeds, check out the official documentation:

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :width (Integer)

    the width of the frame

  • :height (Integer)

    the height of the frame

  • :frameborder (Integer)

    the frameborder of the frame

  • :allowtransparency (Boolean)

    toggle frame transparency

  • :view (nil|String|Symbol)

    specific view option for iframe

  • :theme (nil|String|Symbol)

    specific theme option for iframe

See Also:


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/rspotify/base.rb', line 138

def embed(options = {})
  default_options = {
    width: 300,
    height: 380,
    frameborder: 0,
    allowtransparency: true,
    view: nil,
    theme: nil
  }
  options = default_options.merge(options)

  src = "https://embed.spotify.com/?uri=#{@uri}"
  src << "&view=#{options[:view]}" unless options[:view].nil?
  src << "&theme=#{options[:theme]}" unless options[:theme].nil?

  template = <<-HTML
    <iframe
      src="#{src}"
      width="#{options[:width]}"
      height="#{options[:height]}"
      frameborder="#{options[:frameborder]}"
      allowtransparency="#{options[:allowtransparency]}">
    </iframe>
  HTML

  template.gsub(/\s+/, " ").strip
end

#respond_to?(method_name, include_private_methods = false) ⇒ Boolean

Overrides Object#respond_to? to also consider methods dynamically generated by #method_missing

Returns:

  • (Boolean)

202
203
204
205
206
# File 'lib/rspotify/base.rb', line 202

def respond_to?(method_name, include_private_methods = false)
  attr = "@#{method_name}"
  return super if method_name.match(/[\?!]$/) || !instance_variable_defined?(attr)
  true
end