Sha256: 0d7d7e0dd7d6c7fbf65dc39e13ec35f565867f8749a3f098f1bec957bc63893f

Contents?: true

Size: 1.57 KB

Versions: 2

Compression:

Stored size: 1.57 KB

Contents

require "delegate"

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
    
    # @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 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
    
    def json
      raise StandardError, 'No JSON library initialized' unless URL.json_handler
      URL.json_handler.new(self).parse
    end
    
  end
  
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
url-0.2.1 lib/url/response.rb
url-0.2.0 lib/url/response.rb