Class: Wrest::Uri

Inherits:
Object
  • Object
show all
Defined in:
lib/wrest/uri.rb

Overview

Wrest::Uri provides a simple api for REST calls. String#to_uri is a convenience method to build a Wrest::Uri from a string url.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri_string) ⇒ Uri

Returns a new instance of Uri.



16
17
18
# File 'lib/wrest/uri.rb', line 16

def initialize(uri_string)
  @uri = URI.parse(uri_string)
end

Instance Attribute Details

#uriObject (readonly)

Returns the value of attribute uri.



15
16
17
# File 'lib/wrest/uri.rb', line 15

def uri
  @uri
end

Instance Method Details

#==(other) ⇒ Object



24
25
26
27
# File 'lib/wrest/uri.rb', line 24

def ==(other)
  return false if other.class != self.class
  return other.uri == self.uri
end

#delete(headers = {}) ⇒ Object



47
48
49
# File 'lib/wrest/uri.rb', line 47

def delete(headers = {})
  do_request 'delete', @uri.request_uri, headers.stringify_keys
end

#do_request(method, url, *args) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/wrest/uri.rb', line 51

def do_request(method, url, *args)
  response = nil

  Wrest.logger.info  "#{method} -> #{url}"
  time = Benchmark.realtime { response = Wrest::Response.new(http.send(method, url, *args)) }
  Wrest.logger.info "--> %d %s (%d %.2fs)" % [response.code, response.message, response.body ? response.body.length : 0, time]

  response
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/wrest/uri.rb', line 20

def eql?(other)
  self == other
end

#get(parameters = {}, headers = {}) ⇒ Object

Make a HTTP get request to this URI. Remember to escape the parameter strings using URI.escape



35
36
37
# File 'lib/wrest/uri.rb', line 35

def get(parameters = {}, headers = {})
  do_request 'get', parameters.empty? ? @uri.request_uri : "#{@uri.request_uri}?#{parameters.to_query}", headers.stringify_keys
end

#hashObject



29
30
31
# File 'lib/wrest/uri.rb', line 29

def hash
  self.uri.hash + self.class.object_id
end

#httpObject



65
66
67
68
69
70
71
72
# File 'lib/wrest/uri.rb', line 65

def http
  http = Net::HTTP.new(@uri.host, @uri.port)
  if https?
    http.use_ssl     = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  http
end

#https?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/wrest/uri.rb', line 61

def https?
  @uri.is_a?(URI::HTTPS)
end

#post(body = '', headers = {}) ⇒ Object



43
44
45
# File 'lib/wrest/uri.rb', line 43

def post(body = '', headers = {})
  do_request 'post', @uri.request_uri, body.to_s, headers.stringify_keys
end

#put(body = '', headers = {}) ⇒ Object



39
40
41
# File 'lib/wrest/uri.rb', line 39

def put(body = '', headers = {})
  do_request 'put', @uri.request_uri, body.to_s, headers.stringify_keys
end