Class: URL::Response

Inherits:
String
  • Object
show all
Defined in:
lib/url/response.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str, args = {}) ⇒ Response

Returns a new instance of Response.

Parameters:

  • body (String)

    The body of the response object, main string

  • args (Hash) (defaults to: {})

    Additional arguments: :time,:code,:response,:url

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/url/response.rb', line 40

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

Instance Attribute Details

#codeObject (readonly)

The http code return



18
19
20
# File 'lib/url/response.rb', line 18

def code
  @code
end

#responseObject (readonly)

The response object generated by the handler



22
23
24
# File 'lib/url/response.rb', line 22

def response
  @response
end

#timeObject (readonly)

The time taken for the request



14
15
16
# File 'lib/url/response.rb', line 14

def time
  @time
end

#urlObject (readonly)

The url which generated this response



26
27
28
# File 'lib/url/response.rb', line 26

def url
  @url
end

#url_objObject (readonly)

The url object used to create the response



30
31
32
# File 'lib/url/response.rb', line 30

def url_obj
  @url_obj
end

Instance Method Details

#connection_refusedObject

This is set to true if the target server was not reachable



34
35
36
# File 'lib/url/response.rb', line 34

def connection_refused
  @connection_refused || code == 0
end

#jsonObject

Attempt to parse the response as json

Raises:

  • (StandardError)


64
65
66
67
# File 'lib/url/response.rb', line 64

def json
  raise StandardError, 'No JSON library initialized' unless URL.json_handler
  @json ||= URL.json_handler.new(self).parse
end

#success?Boolean Also known as: successful?

Compares #code to 2xx

Returns:

  • (Boolean)


55
56
57
58
59
# File 'lib/url/response.rb', line 55

def success?
  return @successful if @successful
  
  (200..299).include?(code)
end