Sha256: f1e17e766ed7cdcfd46ca498715b6b1c3b243e99df68acc756d1241f727e15a2

Contents?: true

Size: 1.96 KB

Versions: 4

Compression:

Stored size: 1.96 KB

Contents

class URL
  
  # The Response class is a deleegate to string which also contains metadata about the request.
  # These methods are also available
  # * body
  # * code - http code
  # * response - the original response object from whatever handler you chose
  # * time - time taken to make call
  # * success? - whether the http code is 2xx
  # * url - the URL the object was gotten from
  class Response < DelegateClass(String)
    # The time taken for the request
    # @returns [Integer]
    attr_reader :time
    
    # The http code return
    # @returns [Integer] eg. 200, 404, 500, 503
    attr_reader :code
    
    # The response object generated by the handler
    # @returns [Net::HTTPResponse,Typhoeus::Response]
    attr_reader :response
    
    # The url which generated this response
    # @returns [String]
    attr_reader :url

    # The url object used to create the response
    # @returns [URL]
    attr_reader :url_obj

    # This is set to true if the target server was not reachable
    # @returns [Boolean]
    def connection_refused
      @connection_refused || code == 0
    end
    
    # @param [String] body The body of the response object, main string
    # @param [Hash] args Additional arguments: :time,:code,:response,:url
    def initialize(str,args={})
      if str.is_a?(Hash)
        args = str
        str = args[:body]
      end
      
      raise ArgumentError, "No string provided" unless str
      super(str)
      args.each do |key, value|
        instance_variable_set "@#{key}", value
      end
    end
    
    # Compares {Response#code} to 2xx
    # @returns [true,false]
    def success?
      return @successful if @successful
      
      (200..299).include?(code)
    end
    alias_method :successful?, :success?
    
    # Attempt to parse the response as json
    # @returns [Hash]
    def json
      raise StandardError, 'No JSON library initialized' unless URL.json_handler
      @json ||= URL.json_handler.new(self).parse
    end
    
  end
  
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.4.0/gems/url-0.3.2/lib/url/response.rb
url-0.3.2 lib/url/response.rb
url-0.3.1 lib/url/response.rb
url-0.3.0 lib/url/response.rb