Sha256: 14f83e0f94c36907da2cc604aa2554c95776596618b6d9b55defdf61cd947ae7

Contents?: true

Size: 1.02 KB

Versions: 6

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: true

require "addressable/uri"
require "ipaddr"
require "public_suffix"
require "resolv"

module Apullo
  class Target
    attr_reader :id

    def initialize(id)
      @id = id
    end

    def ipv4
      @ipv4 ||= resolve
    end

    def host
      @host ||= uri&.host
    end

    def scheme
      @scheme ||= uri&.scheme
    end

    def url
      @url ||= uri&.to_s
    end

    def uri
      @uri ||= Addressable::URI.parse(_url)
    rescue Addressable::URI::InvalidURIError => _e
      nil
    end

    def valid?
      uri && (ip? | domain?)
    end

    private

    def _url
      @_url ||= id.start_with?("http://", "https://") ? id : "http://#{id}"
    end

    def ip?
      IPAddr.new host
      true
    rescue IPAddr::InvalidAddressError => _e
      false
    end

    def domain?
      return false if host.match? /[0-9]\z/

      PublicSuffix.valid?(host, default_rule: nil)
    end

    def resolve
      Resolv.getaddress uri&.host
    rescue Resolv::ResolvError => _e
      nil
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
apullo-0.1.5 lib/apullo/target.rb
apullo-0.1.4 lib/apullo/target.rb
apullo-0.1.3 lib/apullo/target.rb
apullo-0.1.2 lib/apullo/target.rb
apullo-0.1.1 lib/apullo/target.rb
apullo-0.1.0 lib/apullo/target.rb