[英]Begin, Rescue with API endpoint
這是我的方法:
def get_video_duration
@time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]
format_duration
end
我需要在用begin
, rescue
塊包裝它時寫出“更好”的方法,以便@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.