【问题标题】:How to check for nil on an object?如何检查对象上的 nil?
【发布时间】:2019-07-09 15:01:47
【问题描述】:

我执行以下调用来获取一个 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。

【问题讨论】:

  • 你是说你试过spotify_track.present?spotify_track.acousticness.present?
  • @Btuman spotify_track.acousticness.present?
  • 调用成功后,spotify_track.acousticness.class 返回什么?
  • @Btuman =&gt; Float
  • (这实际上是我的一个脑放屁,因为它总是会返回 true)。查看文档,在查看他们的文档/代码后,我唯一的猜测是 raw_response 变量:RSpotify.raw_response = true,它应该为您提供一个可以更好玩的对象。除此之外,我会考虑在他们的 github 页面上打开一个问题,因为他们似乎可能错误地实现了这一点

标签: ruby-on-rails ruby rubygems rest-client


【解决方案1】:

你可以拯救它并添加一些代码,

rescue RestClient::ExceptionWithResponse => err

参考rest-client#response-callbacks-error-handling

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    相关资源
    最近更新 更多