Class: TMS::Connection

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Connection

Returns a new instance of Connection.



13
14
15
16
17
18
19
# File 'lib/tms_client/connection.rb', line 13

def initialize(opts={})
  self.auth_token = opts[:auth_token]
  self.api_root = opts[:api_root]
  self.logger = opts[:logger]
  self.debug = opts[:debug]
  setup_connection
end

Instance Attribute Details

#api_rootObject

Returns the value of attribute api_root.



2
3
4
# File 'lib/tms_client/connection.rb', line 2

def api_root
  @api_root
end

#auth_tokenObject

Returns the value of attribute auth_token.



2
3
4
# File 'lib/tms_client/connection.rb', line 2

def auth_token
  @auth_token
end

#connectionObject

Returns the value of attribute connection.



2
3
4
# File 'lib/tms_client/connection.rb', line 2

def connection
  @connection
end

#debugObject

Returns the value of attribute debug.



2
3
4
# File 'lib/tms_client/connection.rb', line 2

def debug
  @debug
end

#loggerObject

Returns the value of attribute logger.



2
3
4
# File 'lib/tms_client/connection.rb', line 2

def logger
  @logger
end

Instance Method Details

#dump_headers(headers) ⇒ Object



43
44
45
# File 'lib/tms_client/connection.rb', line 43

def dump_headers(headers)
  headers.map { |k, v| "#{k}: #{v.inspect}" }.join("\n")
end

#get(href) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/tms_client/connection.rb', line 4

def get(href)
  resp = connection.get("#{href}.json")
  if resp.status != 200
    raise RecordNotFound.new("Could not find resource at #{href} (status #{resp.status})")
  else
    resp.body
  end
end

#setup_connectionObject



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/tms_client/connection.rb', line 21

def setup_connection
  self.connection = Faraday.new(:url => self.api_root) do |faraday|
    faraday.use TMS::Logger, self.logger if self.logger
    faraday.request :json
    setup_logging(faraday)
    faraday.headers['X-AUTH-TOKEN'] = auth_token
    faraday.headers[:user_agent] = "GovDelivery Ruby TMS::Client #{TMS::VERSION}"
    faraday.response :json, :content_type => /\bjson$/
    faraday.adapter :net_http
  end
end

#setup_logging(faraday) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/tms_client/connection.rb', line 33

def setup_logging(faraday)
  faraday.use FaradayMiddleware::Instrumentation, {:name => 'tms_client'}
  ActiveSupport::Notifications.subscribe('tms_client') do |name, starts, ends, _, env|
    duration = ends - starts
    logger.info "#{env[:method].to_s.upcase.ljust(7)}#{env[:status].to_s.ljust(4)}#{env[:url]} (#{duration} seconds)"
    logger.debug('response headers') { JSON.pretty_generate env[:response_headers] }
    logger.debug('response body') { env[:body] }
  end
end