Sha256: 82c3b3097e4a07ff7ea636f98e76dae463e5128dea7f622f3518b1a64aa16c27

Contents?: true

Size: 1.58 KB

Versions: 9

Compression:

Stored size: 1.58 KB

Contents

require 'uri'

module Useless
  module Doc

    # +Doc::Router+ determines the doc URL for an API and vice versa via
    # the #doc_for_api and #api_for_doc methods, respectively.
    #
    module Router
      def self.default
        @default ||= Doc::Router::Default.new
      end

      def self.uri_for(raw_url)
        url = raw_url.dup

        unless url =~ /^https?:\/\//
          url = 'http://' + url
        end

        URI(url)
      end

      def doc_for_api(url)
      end

      def api_for_doc(url)
      end

      class Default
        include Doc::Router

        def initialize(*supported_urls)
          @supported_urls = supported_urls
        end

        def doc_for_api(url)
          return nil unless supported_url?(url)
          uri = Router.uri_for(url)
          host = uri.host
          new_host = host.
            split('.').
            insert(-3, 'doc').
            join('.')
          "#{uri.scheme}://#{new_host}#{uri.path}"
        end

        def api_for_doc(url)
          uri = Router.uri_for(url)
          host = uri.host
          parts = host.split('.')
          parts.slice!(-3) if parts[-3] == 'doc'
          new_host = parts.join('.')
          new_url = "#{uri.scheme}://#{new_host}#{uri.path}"
          new_url if supported_url?(new_url)
        end

        private

        def supported_url?(url)
          if @supported_urls.nil? or @supported_urls.empty?
            true
          else
            @supported_urls.any? do |supported_url|
              url =~ Regexp.new(supported_url)
            end
          end
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
useless-doc-0.7.0 lib/useless/doc/router.rb
useless-doc-0.6.5 lib/useless/doc/router.rb
useless-doc-0.6.4 lib/useless/doc/router.rb
useless-doc-0.6.3 lib/useless/doc/router.rb
useless-doc-0.6.2 lib/useless/doc/router.rb
useless-doc-0.6.1 lib/useless/doc/router.rb
useless-doc-0.6.0 lib/useless/doc/router.rb
useless-doc-0.5.0 lib/useless/doc/router.rb
useless-doc-0.4.0 lib/useless/doc/router.rb