Reputation: 15151
To get favicon binary I wrote like this.
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
But I think it's a bit redundant to write rescue
clause for each url.
How can I write it more succinct?
Upvotes: 0
Views: 28
Reputation: 2125
One way would be to extract the portion that raises exceptions into a separate method, like 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
Upvotes: 1