Created
September 18, 2012 16:42
-
-
Save tranngocsam/3744205 to your computer and use it in GitHub Desktop.
Carrierwave validate remote url - Tested with v0.5.8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################################# | |
###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