我执行以下调用以获取 Ruby 对象,该对象从 Spotify 的 API 返回数据:
spotify_track = RSpotify::AudioFeatures.find('3RmAqYZZjiSyMV40hm6rDL')
返回:
#<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">
当我尝试获取 nil
的属性之一时,出现 404 错误:
> spotify_track.acousticness
Traceback (most recent call last):
1: from (irb):25
RestClient::NotFound (404 Not Found)
那么,如何检查属性是否为 nil
?
spotify_track.acousticness.present?
、spotify_track.acousticness.blank?
和 spotify_track.try(:acousticness)
都是常见的东西返回相同的 RestClient 404 错误。
我正在使用 RSpotify gem,它使用 REST Client gem 。
最佳答案
你可以拯救它并向它添加一些代码,
rescue RestClient::ExceptionWithResponse => err
关于ruby-on-rails - 如何检查对象是否为 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56955480/