Class: Weavr::Connection

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Connection

Returns a new instance of Connection.



6
7
8
9
10
# File 'lib/weavr/connection.rb', line 6

def initialize(options = {})
  @host = options[:host]
  @port = options[:port]
  establish_connection(options[:username], options[:password])
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



4
5
6
# File 'lib/weavr/connection.rb', line 4

def host
  @host
end

#httpObject (readonly)

Returns the value of attribute http.



4
5
6
# File 'lib/weavr/connection.rb', line 4

def http
  @http
end

#portObject (readonly)

Returns the value of attribute port.



4
5
6
# File 'lib/weavr/connection.rb', line 4

def port
  @port
end

Instance Method Details

#base_urlObject



21
22
23
# File 'lib/weavr/connection.rb', line 21

def base_url
  "http://#{host}:#{port}/api/v1"
end

#establish_connection(user, password) ⇒ Object



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

def establish_connection(user, password)
  @http ||= Faraday.new(url: base_url, headers: request_headers) do |conn|
    conn.request  :basic_auth, user, password
    conn.response :json
    conn.response :logger, Weavr.log
    conn.adapter  Faraday.default_adapter
  end
end

#request_headersObject



25
26
27
# File 'lib/weavr/connection.rb', line 25

def request_headers
  { 'X-Requested-By' => "Weavr v#{Weavr::VERSION}" }
end

#resource(action, path, data = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/weavr/connection.rb', line 29

def resource(action, path, data = {})
  resp = http.send(action, path) do |req|
    Weavr.log.info "payload: #{data}" if data
    req.body = data.to_json if data
  end
  Weavr.log.info "body: #{resp.body}"
  Response.handle(resp.status, resp.headers, resp.body)
rescue Faraday::ConnectionFailed
  raise ConnectionError.new "Could not reach Ambari API at #{host}:#{port}"
end