Class: Changebase::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/changebase/connection.rb

Overview

Changebase::Connection is a low-level API. It provides basic HTTP #get, #post, #put, and #delete calls to the an HTTP(S) Server. It can also provides basic error checking of responses.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Connection

Initialize a connection Changebase.

Options:

  • :url - An optional url used to set the protocol, host, port, and api_key

  • :host - The default is to connect to 127.0.0.1.

  • :port - Defaults to 80.

  • :use_ssl - Defaults to true.

  • :api_key - An optional token to send in the ‘Api-Key` header

  • :user_agent - An optional string. Will be joined with other

    User-Agent info.
    


68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/changebase/connection.rb', line 68

def initialize(config)
  if config[:url]
    uri = URI.parse(config.delete(:url))
    config[:api_key] ||= (uri.user ? CGI.unescape(uri.user) : nil)
    config[:host]    ||= uri.host
    config[:port]    ||= uri.port
    config[:use_ssl] ||= (uri.scheme == 'https')
  end

  [:api_key, :host, :port, :use_ssl, :user_agent].each do |key|
    self.instance_variable_set(:"@#{key}", config[key])
  end

  @connection = Net::HTTP.new(host, port)
  @connection.max_retries         = 0
  @connection.open_timeout        = 5
  @connection.read_timeout        = 30
  @connection.write_timeout       = 5
  @connection.ssl_timeout         = 5
  @connection.keep_alive_timeout  = 30
  @connection.use_ssl = use_ssl
  true
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



54
55
56
# File 'lib/changebase/connection.rb', line 54

def api_key
  @api_key
end

#hostObject (readonly)

Returns the value of attribute host.



54
55
56
# File 'lib/changebase/connection.rb', line 54

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



54
55
56
# File 'lib/changebase/connection.rb', line 54

def port
  @port
end

#use_sslObject (readonly)

Returns the value of attribute use_ssl.



54
55
56
# File 'lib/changebase/connection.rb', line 54

def use_ssl
  @use_ssl
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


96
97
98
# File 'lib/changebase/connection.rb', line 96

def active?
  @connection.active?
end

#connect!Object



92
93
94
# File 'lib/changebase/connection.rb', line 92

def connect!
  @connection.start
end

#delete(path, &block) ⇒ Object

Send a DELETE request to path via Connection#send_request. See Connection#send_request for more details on how the response is handled

Paramaters
  • path - The path on the server to POST to.

  • block - Optional, See Connection#send_request

Return Value

See Connection#send_request

Examples:

#!ruby
connection.delete('/example') # => #<Net::HTTP::Response>

connection.delete('/404') # => raises Changebase::Exception::NotFound

connection.delete('/act') do |response|
  # ...
end


330
331
332
333
334
# File 'lib/changebase/connection.rb', line 330

def delete(path, &block)
  request = Net::HTTP::Delete.new(path)

  send_request(request, nil, &block)
end

#disconnect!Object



105
106
107
# File 'lib/changebase/connection.rb', line 105

def disconnect!
  @connection.finish if @connection.active?
end

#get(path, params = '', &block) ⇒ Object

Send a GET request to path via Connection#send_request. See Connection#send_request for more details on how the response is handled.

Paramaters
  • path - The path on the server to GET to.

  • params - Either a String, Hash, or Ruby Object that responds to

    #to_param. Appended on the URL as query params
    
  • block - An optional block to call with the Net::HTTPResponse object.

Return Value

See Connection#send_request

Examples:

#!ruby
connection.get('/example') # => #<Net::HTTP::Response>

connection.get('/example', 'query=stuff') # => #<Net::HTTP::Response>

connection.get('/example', {:query => 'stuff'}) # => #<Net::HTTP::Response>

connection.get('/404') # => raises Changebase::Exception::NotFound

connection.get('/act') do |response|
  # ...
end


228
229
230
231
232
233
# File 'lib/changebase/connection.rb', line 228

def get(path, params='', &block)
  params ||= ''
  request = Net::HTTP::Get.new(path + '?' + params.to_param)

  send_request(request, nil, &block)
end

#post(path, body = nil, &block) ⇒ Object

Send a POST request to path via Connection#send_request. See Connection#send_request for more details on how the response is handled.

Paramaters
  • path - The path on the server to POST to.

  • body - Optional, See Connection#send_request.

  • block - Optional, See Connection#send_request

Return Value

See Connection#send_request

Examples:

#!ruby
connection.post('/example') # => #<Net::HTTP::Response>

connection.post('/example', 'body') # => #<Net::HTTP::Response>

connection.post('/example', #<IO Object>) # => #<Net::HTTP::Response>

connection.post('/example', {:example => 'data'}) # => #<Net::HTTP::Response>

connection.post('/404') # => raises Changebase::Exception::NotFound

connection.post('/act') do |response|
  # ...
end


265
266
267
268
269
# File 'lib/changebase/connection.rb', line 265

def post(path, body=nil, &block)
  request = Net::HTTP::Post.new(path)

  send_request(request, body, &block)
end

#put(path, body = nil, *valid_response_codes, &block) ⇒ Object

Send a PUT request to path via Connection#send_request. See Connection#send_request for more details on how the response is handled.

Paramaters
  • path - The path on the server to POST to.

  • body - Optional, See Connection#send_request.

  • block - Optional, See Connection#send_request

Return Value

See Connection#send_request

Examples:

#!ruby
connection.put('/example') # => #<Net::HTTP::Response>

connection.put('/example', 'body') # => #<Net::HTTP::Response>

connection.put('/example', #<IO Object>) # => #<Net::HTTP::Response>

connection.put('/example', {:example => 'data'}) # => #<Net::HTTP::Response>

connection.put('/404') # => raises Changebase::Exception::NotFound

connection.put('/act') do |response|
  # ...
end


301
302
303
304
305
# File 'lib/changebase/connection.rb', line 301

def put(path, body=nil, *valid_response_codes, &block)
  request = Net::HTTP::Put.new(path)

  send_request(request, body, &block)
end

#reconnect!Object



100
101
102
103
# File 'lib/changebase/connection.rb', line 100

def reconnect!
  disconnect!
  connect!
end

#send_request(request, body = nil, &block) ⇒ Object

Sends a Net::HTTPRequest to the server. The headers returned from Connection#request_headers are automatically added to the request. The appropriate error is raised if the response is not in the 200..299 range.

Paramaters
  • request - A Net::HTTPRequest to send to the server

  • body - Optional, a String, IO Object, or a Ruby object which is

    converted into JSON and sent as the body
    
  • block - An optional block to call with the Net::HTTPResponse object.

Return Value

Returns the return value of the &block if given, otherwise the response object (a Net::HTTPResponse)

Examples:

#!ruby
connection.send_request(#<Net::HTTP::Get>) # => #<Net::HTTP::Response>

connection.send_request(#<Net::HTTP::Get @path="/404">) # => raises Changebase::Exception::NotFound

# this will still raise an exception if the response_code is not valid
# and the block will not be called
connection.send_request(#<Net::HTTP::Get>) do |response|
  # ...
end

# The following example shows how to stream a response:
connection.send_request(#<Net::HTTP::Get>) do |response|
  response.read_body do |chunk|
    io.write(chunk)
  end
end


156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/changebase/connection.rb', line 156

def send_request(request, body=nil, &block)
  request_headers.each { |k, v| request[k] = v }
  request['Content-Type'] ||= 'application/json'

  if body.is_a?(IO)
    request['Transfer-Encoding'] = 'chunked'
    request.body_stream =  body
  elsif body.is_a?(String)
    request.body = body
  elsif body
    request.body = JSON.generate(body)
  end

  return_value = nil
  begin
    close_connection = false
    @connection.request(request) do |response|
      # if response['Deprecation-Notice']
      #   ActiveSupport::Deprecation.warn(response['Deprecation-Notice'])
      # end

      validate_response_code(response)

      # Get the cookies
      response.each_header do |key, value|
        case key.downcase
        when 'connection'
          close_connection = (value == 'close')
        end
      end

      if block_given?
        return_value = yield(response)
      else
        return_value = response
      end
    end
    @connection.finish if close_connection
  end

  return_value
end

#user_agentObject

Returns the User-Agent of the client. Defaults to: “Rubygems/changebase@GEM_VERSION Ruby@RUBY_VERSION-pPATCH_LEVEL RUBY_PLATFORM”



111
112
113
114
115
116
117
118
# File 'lib/changebase/connection.rb', line 111

def user_agent
  [
    @user_agent,
    "Rubygems/changebase@#{Changebase::VERSION}",
    "Ruby@#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}",
    RUBY_PLATFORM
  ].compact.join(' ')
end