1

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?

4

1 回答 1

3

假设您只想验证URLs指向图像类型的文件。

例如:http://www.xyz.com/logo.pnghttp://www.xyz.com/logo.gifhttp://www.xyz.com/logo.jpg

这是解决方案:

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

上面的例子只允许 url 指向带有扩展名的图像,.png or .gif or .jpg而 rest 将被设置为IMAGE_NOT_FOUND. 如果您愿意,可以添加更多扩展。

于 2014-03-16T21:50:19.780 回答