Sha256: 3cf3c484470e00eb08ae4166a7c32c1919d88ce591f09163688b9bf26d5c0b5c

Contents?: true

Size: 1.7 KB

Versions: 1

Compression:

Stored size: 1.7 KB

Contents

require 'uri'

module Earl
  class URL
    def initialize( source )
      @uri = URI.parse( source )
    end

    def scheme
      StringInquirer.new( parts[ :scheme ] ) rescue nil
    end
    def scheme=( value )
      parts[ :scheme ] = value
    end
    def scheme?
      !( parts[ :scheme ].nil? || parts[ :scheme ].empty? )
    end

    def subdomain
      StringInquirer.new( parts[ :subdomain ] ) rescue nil
    end
    def subdomain=( value )
      parts[ :subdomain ] = value
    end
    def subdomain?
      !( parts[ :subdomain ].nil? || parts[ :subdomain ].empty? )
    end

    def host
      StringInquirer.new( [ domain, top_level_domain ].compact.join( '.' ) ) rescue nil
    end
    def host=( value )
      parts[ :domain ], parts[ :top_level_domain ] = value.split( '.' )
    end
    def host?
      [ domain, top_level_domain ].compact.any?
    end

    def to_s
      out = ''
      out << "#{scheme}://" if scheme?
      out << [ subdomain, domain, top_level_domain ].compact.join( '.' )
    end

    protected

    def domain
      StringInquirer.new( parts[ :domain ] ) rescue nil
    end
    def top_level_domain
      StringInquirer.new( parts[ :top_level_domain ] ) rescue nil
    end

    def parts
      @parts ||= begin
        { }.tap do |hsh|
          hsh[ :scheme    ] = @uri.scheme
          hsh[ :subdomain ], hsh[ :domain ], hsh[ :top_level_domain ] = domain_parts
        end
      end
    end

    def domain_parts
      parts = host_parts || [ nil ]
      parts << nil      if parts.size == 1
      parts.unshift nil if parts.size == 2
      parts
    end

    def host_parts
      if @uri.host
        @uri.host.split '.'
      elsif @uri.path
        @uri.path.split '.'
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
earl-0.1.0 lib/earl/url.rb