这是我的方法:
def get_video_duration
@time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]
format_duration
end
begin
我需要用,块来“更好地”编写这个方法,rescue
以便@time
根据 API 的响应,它可能是 nil 。
Yes, possible using inline rescue
clause.
def get_video_duration
@time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"] rescue nil
format_duration
end
Or better explicitly do it.
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