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 19 |
# 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) .reverse_merge!(accept_array: false) super() end |
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/validate_url.rb', line 21 def validate_each(record, attribute, value) schemes = [*.fetch(:schemes)].map(&:to_s) if value.respond_to?(:each) # Error out if we're not allowing arrays if !.include?(:accept_array) || !.fetch(:accept_array) record.errors.add(attribute, :url, **(value)) end # We have to manually handle `:allow_nil` and `:allow_blank` since it's not caught by # ActiveRecord's own validators. We do that by just removing all the nil's if we want to # allow them so it's not passed on later. value = value.reject(&:nil?) if .include?(:allow_nil) && .fetch(:allow_nil) value = value.reject(&:blank?) if .include?(:allow_blank) && .fetch(:allow_blank) result = value.flat_map { |v| validate_url(record, attribute, v, schemes) } errors = result.reject(&:nil?) return errors.any? ? errors.first : true end validate_url(record, attribute, value, schemes) end |