0

这是我的方法:

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

begin我需要用,块来“更好地”编写这个方法,rescue以便@time根据 API 的响应,它可能是 nil 。

4

2 回答 2

2

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
于 2014-01-27T14:39:33.907 回答
1

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

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
于 2014-01-27T14:48:43.457 回答