Sha256: 3f08e5e454e69b02fe8d8db1e5ddfb039cca36addaffacbc5cb112264b79d013

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

module URLCanonicalize
  # Manage the URL into a URI with local exception handling
  class URI
    class << self
      def parse(url)
        uri = ::URI.parse decorate(url)
        uri if valid? uri
      rescue ::URI::InvalidURIError => e
        new_exception = URLCanonicalize::Exception::URI.new("#{e.class}: #{e.message}")
        new_exception.set_backtrace e.backtrace
        raise new_exception
      end

      private

      def valid?(uri)
        raise URLCanonicalize::Exception::URI, "#{uri} must be http or https" unless VALID_CLASSES.include?(uri.class)
        raise URLCanonicalize::Exception::URI, "Missing host name in #{uri}" unless uri.host
        raise URLCanonicalize::Exception::URI, "Empty host name in #{uri}" if uri.host.empty?

        true
      end

      def decorate(url)
        return url if url.include? COLON

        "http://#{url}" # Add protocol if we just receive a host name
      end

      VALID_CLASSES = [::URI::HTTP, ::URI::HTTPS].freeze
      COLON = ':'
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
url_canonicalize-1.0.0 lib/url_canonicalize/uri.rb