要获得favicon二元,我就是这样写的。
def favicon_url_from_link
# get a url from link tag
URI('http://example.com/common/favicon.png')
end
def favicon_url_from_path
URI('http://example.com/favicon.ico')
end
def favicon_binary_from_link
favicon_url_from_link&.read
rescue OpenURI::HTTPError
nil
end
def favicon_binary_from_path
favicon_url_from_path&.read
rescue OpenURI::HTTPError
nil
end
def favicon_binary
favicon_binary_from_link || favicon_binary_from_path
end
但我认为为每个网址编写rescue
子句有点多余。
我怎么能写得更简洁呢?
答案 0 :(得分:1)
一种方法是将引发异常的部分提取到单独的方法中,例如read_url
:
def favicon_binary_from_link
read_url(favicon_url_from_link)
end
def favicon_binary_from_path
read_url(favicon_url_from_path)
end
def read_url(url)
url&.read
rescue OpenURI::HTTPError
nil
end
def favicon_binary
favicon_binary_from_link || favicon_binary_from_path
end