Using official guide for custom validations I would recommend to create url_validator.rb
in your app/validators
with the following content:
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'must be a valid URL') unless url_valid?(value)
end
def url_valid?(url)
uri = URI.parse(url) rescue false
uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
end
end
Thereafter you may validate thumbnail
attribute like this:
class SearchResult < ActiveRecord::Base
validates :thumbnail, url: true, allow_blank: true
end
Also you may improve url_valid?
method to consider extension whitelist via regex (however I would create another validator for this, e.g. image_url_validator.rb
to keep basic url validator).
EDIT:
app/validators/image_url_validator.rb
class ImageUrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'must be a valid URL (only jpg and gif)') unless url_valid?(value)
end
def url_valid?(url)
uri = URI.parse(url) rescue false
(uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)) && uri.to_s.match(/\.jpg|\.gif/)
end
end
app/models/search_result.rb
class SearchResult < ActiveRecord::Base
validates :thumbnail, image_url: true, allow_blank: true
end
Key benefit of this approach is that you may reuse this custom validations for different attributes in different models.