Sha256: d205e7d8f6369cbb3d9cf2a8a4f8ee8a01d2682473354e6b5a7173fdf11934e7

Contents?: true

Size: 1.74 KB

Versions: 10

Compression:

Stored size: 1.74 KB

Contents

require 'public_suffix'
require 'delegate'
require 'uri'

module PageRankr
  class Site
    COMPONENTS = [:scheme, :subdomain, :domain, :port, :path, :query, :fragment]

    def initialize(site)
      site = "http://#{site}" unless site =~ /:\/\//
      @uri = URI.parse(site)
      @domain = PublicSuffix.parse(@uri.host || "")

      @domain.valid? or raise DomainInvalid, "The domain provided is invalid.1"
    rescue PublicSuffix::DomainInvalid, URI::InvalidURIError
      raise DomainInvalid, "The domain provided is invalid."
    end

    def scheme
      @uri.scheme
    end

    def domain
      @domain.domain
    end

    def subdomain
      @domain.subdomain or domain
    end

    def port
      @uri.port
    end

    def path
      @uri.path
    end

    def query
      @uri.query
    end

    def fragment
      @uri.fragment
    end

    def url(supported_components = [:domain])
      components = COMPONENTS & supported_components #get ordered list

      unless components.include?(:subdomain) ^ components.include?(:domain)
        raise SupportedComponentsInvalid, "Either subdomain or domain should be set as a supported component, not both."
      end

      components.inject("") do |url, component|
        url + case component
        when :scheme
          scheme and "#{scheme}://" or ""
        when :domain
          domain
        when :subdomain
          subdomain
        when :port
          port == @uri.default_port and "" or ":#{port}"
        when :path
          path or ""
        when :query
          query and "?#{query}" or ""
        when :fragment
          fragment and "##{fragment}" or ""
        end
      end
    end
  end

  class << self
    def Site(site)
      site.respond_to?(:url) ? site : Site.new(site)
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
PageRankr-4.4.1 lib/page_rankr/site.rb
PageRankr-4.4.0 lib/page_rankr/site.rb
PageRankr-4.3.0 lib/page_rankr/site.rb
PageRankr-4.2.1 lib/page_rankr/site.rb
PageRankr-4.2.0 lib/page_rankr/site.rb
PageRankr-4.1.1 lib/page_rankr/site.rb
PageRankr-4.1.0 lib/page_rankr/site.rb
PageRankr-4.0.0 lib/page_rankr/site.rb
PageRankr-3.2.1 lib/page_rankr/site.rb
PageRankr-3.2.0 lib/page_rankr/site.rb