Sha256: af338cb6f1345ff866eadf3d8c13ecaa7fc6c2ab5c982f6bb96cfba76e9bf550

Contents?: true

Size: 1.16 KB

Versions: 75

Compression:

Stored size: 1.16 KB

Contents

require "active_model"

module ActiveModel
  module Validations
    # Validates that the value is a url
    #
    # Example:
    #
    #   validates :website_url, url: true
    #
    class UrlValidator < EachValidator
      URL_PATTERN = URI::DEFAULT_PARSER.make_regexp(%w[http https]).freeze

      attr_reader :record, :attribute, :value

      def validate_each(record, attribute, value)
        @record = record
        @attribute = attribute
        @value = value

        return if skip?
        return unless validate_url

        nil unless maybe_validate_image_url
      end

      private

      def skip?
        return true if value.nil? && options[:allow_nil]

        true if value.blank? && options[:allow_blank]
      end

      def validate_url
        return true if URL_PATTERN.match?(value)

        record.errors.add attribute, (options[:message] || "is not a valid URL")
        false
      end

      def maybe_validate_image_url
        return true unless options[:image].present?
        return true unless FastImage.type(value).nil?

        record.errors.add(attribute, (options[:message] || "is not a valid image URL"))
        false
      end
    end
  end
end

Version data entries

75 entries across 75 versions & 1 rubygems

Version Path
plutonium-0.12.11 lib/active_model/validations/url_validator.rb
plutonium-0.12.10 lib/active_model/validations/url_validator.rb
plutonium-0.12.9 lib/active_model/validations/url_validator.rb
plutonium-0.12.8 lib/active_model/validations/url_validator.rb
plutonium-0.12.7 lib/active_model/validations/url_validator.rb
plutonium-0.12.5 lib/active_model/validations/url_validator.rb
plutonium-0.12.4 lib/active_model/validations/url_validator.rb
plutonium-0.12.3 lib/active_model/validations/url_validator.rb
plutonium-0.12.2 lib/active_model/validations/url_validator.rb
plutonium-0.12.1 lib/active_model/validations/url_validator.rb
plutonium-0.12.0 lib/active_model/validations/url_validator.rb
plutonium-0.11.2 lib/active_model/validations/url_validator.rb
plutonium-0.11.1 lib/active_model/validations/url_validator.rb
plutonium-0.11.0 lib/active_model/validations/url_validator.rb
plutonium-0.8.0 lib/active_model/validations/url_validator.rb