2

I do the following call to get a Ruby object, which returns data from Spotify's API:

spotify_track = RSpotify::AudioFeatures.find('3RmAqYZZjiSyMV40hm6rDL')

That returns:

#<RSpotify::AudioFeatures:0x00007fe0cc079b30 @acousticness=nil, @analysis_url="https://api.spotify.com/v1/audio-analysis/3RmAqYZZjiSyMV40hm6rDL", @danceability=nil, @duration_ms=35361, @energy=nil, @instrumentalness=nil, @key=1, @liveness=nil, @loudness=-12.186, @mode=1, @speechiness=nil, @tempo=0, @time_signature=nil, @track_href="https://api.spotify.com/v1/tracks/3RmAqYZZjiSyMV40hm6rDL", @valence=nil, @external_urls=nil, @href=nil, @id="3RmAqYZZjiSyMV40hm6rDL", @type="audio_features", @uri="spotify:track:3RmAqYZZjiSyMV40hm6rDL"> 

When I try to get one of the attributes that's nil, I get a 404 error:

> spotify_track.acousticness
Traceback (most recent call last):
        1: from (irb):25
RestClient::NotFound (404 Not Found)

So, how can I check to see if an attribute is nil or not?

The usual things like spotify_track.acousticness.present?, spotify_track.acousticness.blank? and spotify_track.try(:acousticness) all return that same RestClient 404 error.

I'm using the RSpotify gem, which makes use of the REST Client gem.

Shpigford
  • 24,748
  • 58
  • 163
  • 252
  • Are you saying you tried `spotify_track.present?` or `spotify_track.acousticness.present?` – Btuman Jul 09 '19 at 15:05
  • @Btuman `spotify_track.acousticness.present?` – Shpigford Jul 09 '19 at 15:06
  • On a successful call, what does `spotify_track.acousticness.class` return? – Btuman Jul 09 '19 at 15:07
  • @Btuman `=> Float` – Shpigford Jul 09 '19 at 15:14
  • and on an `.spotify_track.acousticness` that returns that 404? – Btuman Jul 09 '19 at 15:15
  • Sorry, if I do `spotify_track.acousticness.class` when that attribute is `nil`, it returns 404. When `acousticness` has a value, then calling `.class` on it, returns `Float`. – Shpigford Jul 09 '19 at 15:21
  • Would you mind trying `spotify_track.respond_to?("acousticness")` – Btuman Jul 09 '19 at 15:37
  • It returns `true`. – Shpigford Jul 09 '19 at 15:42
  • 1
    (that was actually a brain fart on my part, since it would always return true). Looking over the documentation, my only guess after going through their documentation/code is raw_response variable: `RSpotify.raw_response = true`, which should get you an object that you can play with nicer. Beyond that, I would consider opening an issue on their github page, as they seemed to have possibly implemented this incorrectly – Btuman Jul 09 '19 at 15:58

1 Answers1

0

You can rescue and add some code to it,

rescue RestClient::ExceptionWithResponse => err

Refer rest-client#response-callbacks-error-handling

ray
  • 5,454
  • 1
  • 18
  • 40