【问题标题】:Begin, Rescue with API endpoint开始,使用 API 端点进行救援
【发布时间】:2014-01-27 14:38:12
【问题描述】:

这是我的方法:

def get_video_duration
  @time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]
  format_duration
end

我需要将这个方法写得“更好”,用beginrescue 块包装它,这样@time 可以为零,具体取决于API 的响应。

【问题讨论】:

  • 您是要始终执行Panda.get,还是仅在@time 为nil/false 时执行?

标签: ruby rescue


【解决方案1】:

是的,可以使用 inline rescue 子句。

def get_video_duration
    @time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"] rescue nil
    format_duration
end

或者最好明确地这样做。

def get_video_duration
  @time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]
rescue YourException
  @time = nil
  format_duration
end

【讨论】:

  • 你破坏了 OP 的逻辑。在最初的问题中,@time 在任何情况下都存在延迟实例化,无论是否已经设置。
  • @mudasobwa 如果这就是 OP 的意思,我将删除它。让我们等待 OP 回来回应,这不是他想要的。
  • @ArupRakshit - 感谢您的帮助! @time 的惰性实例化是我想要的
  • @dennismonsewicz 这是否解决了您的问题...?现在
【解决方案2】:

也许可以用另一种方法来分解它:

def fetch_video_duration

  Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]

  rescue
    return nil
end

def get_video_duration
  @time ||= fetch_video_duration

  format_duration
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2011-03-11
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多