Home > Back-end >  How to capture on object with a broken image url
How to capture on object with a broken image url

Time:06-17

An API consumes data, which includes an attribute (image_url) used to store an image. However, on occasion that file does not exist.

Is there a way in Ruby to validate an objects of a class - say Article - and NOT process the broken images?

CodePudding user response:

You can use Net::HTTP.get_response to check for response of the potentially broken image

image_url = Article.find(params[:id]).image_url # Potentially broken image url
result = Net::HTTP.get_response(URI.parse(image_url))

And then you can check result.code.

If image exists and available you will get

result.code # => "200"

Otherwise

result.code # => "404" | or any other non-success code

And then do what you want depending on result.code result

  • Related