Class: ActiveModel::Validations::UrlValidator
- Inherits:
-
EachValidator
- Object
- EachValidator
- ActiveModel::Validations::UrlValidator
- Defined in:
- lib/validate_url.rb
Constant Summary collapse
- RESERVED_OPTIONS =
[:schemes, :no_local]
Instance Method Summary collapse
-
#initialize(options) ⇒ UrlValidator
constructor
A new instance of UrlValidator.
- #validate_each(record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ UrlValidator
Returns a new instance of UrlValidator.
11 12 13 14 15 16 17 18 |
# File 'lib/validate_url.rb', line 11 def initialize() .reverse_merge!(schemes: %w(http https)) .reverse_merge!(message: :url) .reverse_merge!(no_local: false) .reverse_merge!(public_suffix: false) super() end |
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/validate_url.rb', line 20 def validate_each(record, attribute, value) schemes = [*.fetch(:schemes)].map(&:to_s) begin uri = URI.parse(value) host = uri && uri.host scheme = uri && uri.scheme valid_raw_url = scheme && value =~ /\A#{URI::regexp([scheme])}\z/ valid_scheme = host && scheme && schemes.include?(scheme) valid_no_local = !.fetch(:no_local) || (host && host.include?('.')) valid_suffix = !.fetch(:public_suffix) || (host && PublicSuffix.valid?(host, :default_rule => nil)) unless valid_raw_url && valid_scheme && valid_no_local && valid_suffix record.errors.add(attribute, .fetch(:message), value: value) end rescue URI::InvalidURIError record.errors.add(attribute, :url, (value)) end end |