2016-06-20 09:34:34 +00:00
|
|
|
# AddressableUrlValidator
|
2016-06-17 13:09:39 +00:00
|
|
|
#
|
2016-06-20 15:25:51 +00:00
|
|
|
# Custom validator for URLs. This is a stricter version of UrlValidator.
|
2016-06-17 13:09:39 +00:00
|
|
|
#
|
2016-06-20 09:34:34 +00:00
|
|
|
# By default, only URLs for http, https, ssh, and git protocols will be considered valid.
|
2016-06-17 13:09:39 +00:00
|
|
|
# Provide a `:protocols` option to configure accepted protocols.
|
|
|
|
#
|
|
|
|
# Example:
|
|
|
|
#
|
|
|
|
# class User < ActiveRecord::Base
|
2016-06-20 09:34:34 +00:00
|
|
|
# validates :personal_url, addressable_url: true
|
2016-06-17 13:09:39 +00:00
|
|
|
#
|
2016-06-20 09:34:34 +00:00
|
|
|
# validates :ftp_url, addressable_url: { protocols: %w(ftp) }
|
2016-06-17 13:09:39 +00:00
|
|
|
#
|
2016-06-20 09:34:34 +00:00
|
|
|
# validates :git_url, addressable_url: { protocols: %w(http https ssh git) }
|
2016-06-17 13:09:39 +00:00
|
|
|
# end
|
|
|
|
#
|
|
|
|
class AddressableUrlValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
unless valid_url?(value)
|
|
|
|
record.errors.add(attribute, "must be a valid URL")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-06-20 15:20:53 +00:00
|
|
|
private
|
|
|
|
|
2016-06-17 13:09:39 +00:00
|
|
|
def valid_url?(value)
|
|
|
|
return false unless value
|
|
|
|
|
|
|
|
value.strip!
|
|
|
|
|
|
|
|
valid_uri?(value) && valid_protocol?(value)
|
|
|
|
rescue Addressable::URI::InvalidURIError
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
2016-06-20 13:31:03 +00:00
|
|
|
def default_options
|
|
|
|
@default_options ||= { protocols: %w(http https ssh git) }
|
|
|
|
end
|
|
|
|
|
2016-06-17 13:09:39 +00:00
|
|
|
def valid_uri?(value)
|
2016-06-20 09:34:34 +00:00
|
|
|
Addressable::URI.parse(value).is_a?(Addressable::URI)
|
2016-06-17 13:09:39 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def valid_protocol?(value)
|
|
|
|
options = default_options.merge(self.options)
|
2016-06-20 15:20:53 +00:00
|
|
|
!!(value =~ /\A#{URI.regexp(options[:protocols])}\z/)
|
2016-06-17 13:09:39 +00:00
|
|
|
end
|
|
|
|
end
|