Sha256: 2de045d23aed551acb723a50b374cc87929650871172ebdf7d9c99f8762dd76c

Contents?: true

Size: 1.33 KB

Versions: 5

Compression:

Stored size: 1.33 KB

Contents

module Contentful
  # This object represents a request that is to be made. It gets initialized by the client
  # with domain specific logic. The client later uses the Request's #url and #query methods
  # to execute the HTTP request.
  class Request
    attr_reader :client, :type, :query, :id

    def initialize(client, endpoint, query = {}, id = nil)
      @client = client
      @endpoint = endpoint
      @absolute = true if @endpoint.start_with?('http')

      @query = if query && !query.empty?
        normalize_query(query)
      end

      if id
        @type = :single
        @id = URI.escape(id)
      else
        @type = :multi
        @id = nil
      end
    end

    # Returns the final URL, relative to a contentful space
    def url
      "#{@endpoint}#{ @type == :single ? "/#{id}" : '' }"
    end

    # Delegates the actual HTTP work to the client
    def get
      client.get(self)
    end

    # Returns true if endpoint is an absolute url
    def absolute?
      !! @absolute
    end

    # Returns a new Request object with the same data
    def copy
      Marshal.load(Marshal.dump(self))
    end


    private

    def normalize_query(query)
      Hash[
        query.map do |key, value|
          [
            key.to_sym,
            value.is_a?(::Array) ? value.join(',') : value
          ]
        end
      ]
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
contentful-0.3.4 lib/contentful/request.rb
contentful-0.3.3 lib/contentful/request.rb
contentful-0.3.2 lib/contentful/request.rb
contentful-0.3.1 lib/contentful/request.rb
contentful-0.3.0 lib/contentful/request.rb