簡體   English   中英

開始使用API​​端點進行救援

[英]Begin, Rescue with API endpoint

這是我的方法:

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

我需要在用beginrescue塊包裝它時寫出“更好”的方法,以便@time可以為零,具體取決於API的響應。

是的,可以使用內聯 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

也許用其他方法將其分解:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM