Question

I have the following class:

require 'uri'

class Images

  IMAGE_NOT_FOUND = '/images/no_image.gif'

  attr_accessor :url

  def initialize(parameters = {})
    @url = parameters.fetch(:url, IMAGE_NOT_FOUND)
    @url = IMAGE_NOT_FOUND unless @url =~/^#{URI::regexp}$/
  end

end

holding URL to image. I have checked some questions and add URL validation, but I need to improve it validating URLs pointing to images only.If validation fails, I want to use default image showing there is some issue.

Note, the current validation of the URL is not working with relative paths. For example, the following url is valid as image source /images/image1.png but the current validation is not recognizing it.

Could anyone tell if this is possible using URI?

Was it helpful?

Solution

Assuming that you want to only validate the URLs pointing to image type of files.

For eg: http://www.xyz.com/logo.png or http://www.xyz.com/logo.gif or http://www.xyz.com/logo.jpg

Here's the solution:

require 'uri'

class Images

  IMAGE_NOT_FOUND = '/images/no_image.gif'

  attr_accessor :url

  def initialize(parameters = {})
    @url = parameters.fetch(:url, IMAGE_NOT_FOUND)
    @url = IMAGE_NOT_FOUND unless ((File.extname(@url) =~/^(.png|.gif|.jpg)$/ )||(@url =~ /^#{URI::regexp}$/))
  end

end

The above example will only allow url's pointing to images with extension .png or .gif or .jpg and rest would be set to IMAGE_NOT_FOUND. Add more extensions if you want to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top