-
-
Save knzconnor/5113293 to your computer and use it in GitHub Desktop.
Totally untested, just forked and tweaked for discussion
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
require 'addressable/uri' | |
#Accepts options[:message] and options[:allowed_protocols] | |
class UriValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
uri = parse_uri(value) | |
if !uri | |
record.errors[attribute] << generic_failure_message | |
elsif !allowed_protocols.include?(uri.scheme) | |
record.errors[attribute] << "must begin with #{allowed_protocols_humanized}" | |
end | |
end | |
private | |
def generic_failure_message | |
options[:message] || "is an invalid URL" | |
end | |
def allowed_protocols_humanized | |
allowed_protocols.to_sentence(:two_words_connector => 'or') | |
end | |
def allowed_protocols | |
@allowed_protocols ||= ([options[:allowed_protocols]].flatten || ['http', 'https']) | |
end | |
def parse_uri | |
Addressable::URI.parse(value) | |
rescue URI::InvalidURIError | |
end | |
end |
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
describe UriValidator do | |
subject do | |
Class.new do | |
include ActiveModel::Validations | |
validates_with UriValidator | |
attr_accessor :url | |
end.new | |
end | |
it "should be valid for a valid http url" do | |
subject.url = 'http://www.google.com' | |
subject.should be_valid | |
end | |
end |
UriValidator#allowed_protocols should be:
def allowed_protocols
@allowed_protocols ||= [(options[:allowed_protocols] || ['http', 'https'])].flatten
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 29 of
uri_validator.rb
should be: