Skip to content

Instantly share code, notes, and snippets.

@tranngocsam
Created September 18, 2012 16:42
Show Gist options
  • Save tranngocsam/3744205 to your computer and use it in GitHub Desktop.
Save tranngocsam/3744205 to your computer and use it in GitHub Desktop.
Carrierwave validate remote url - Tested with v0.5.8
#############################################
###uri_validator file:
#############################################
require 'net/http'
# Thanks Ilya! http://www.igvita.com/2006/09/07/validating-url-in-ruby-on-rails/
# Original credits: http://blog.inquirylabs.com/2006/04/13/simple-uri-validation/
# HTTP Codes: http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPResponse.html
class UriValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
raise(ArgumentError, "A regular expression must be supplied as the :format option of the options hash") unless options[:format].nil? or options[:format].is_a?(Regexp)
configuration = { :message => "is invalid or not responding", :format => URI::regexp(%w(http https)) }
configuration.update(options)
if value =~ configuration[:format]
begin # check header response
case Net::HTTP.get_response(URI.parse(value))
when Net::HTTPSuccess then true
else object.errors.add(attribute, configuration[:message]) and false
end
rescue # Recover on DNS failures..
object.errors.add(attribute, configuration[:message]) and false
end
else
object.errors.add(attribute, configuration[:message]) and false
end
end
end
#################################################################
###image model
#################################################################
require "uri_validator"
class Image < ActiveRecord::Base
attr_accessible :remote_url
attr_accessor :remote_url
attr_writer :remote_url
mount_uploader :image, ImageUploader
validates :remote_url,
:uri => {
:format => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix, :unless => :blank_url?
}
after_validation do
self.remote_image_url = self.remote_url if self.errors[:remote_url].blank?
end
private
def blank_url?
self.remote_url.blank?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment