Class: DeviceDBComms::Shared

Inherits:
Object
  • Object
show all
Defined in:
lib/devicedb_comms/shared.rb

Direct Known Subclasses

Device, Hive, Queue

Instance Method Summary collapse

Constructor Details

#initialize(url = nil, pem_path = nil) ⇒ Shared

Backward compatibility with version <= 0.0.14 TODO Remove arguments



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/devicedb_comms/shared.rb', line 10

def initialize(url = nil, pem_path = nil)
  url ||= DeviceDBComms.configuration.url
  pem_path ||= DeviceDBComms.configuration.pem_file

  if url
    uri = URI.parse(url)

    @http = Net::HTTP.new(uri.host, uri.port)

    if pem_path
      pem = File.read(pem_path)
      @http.use_ssl = true if uri.scheme == 'https'
      @http.cert = OpenSSL::X509::Certificate.new(pem)
      @http.key = OpenSSL::PKey::RSA.new(pem)
      @http.verify_mode = DeviceDBComms.configuration.ssl_verify_mode
    end
  else
    @http = nil
  end
end

Instance Method Details

#get(call) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/devicedb_comms/shared.rb', line 31

def get(call)
  if @http
    begin
      parse_response @http.request_get(call + '.json')
    rescue StandardError => e
      { 'error' => "GET failed: #{e.message}" }
    end
  else
    { 'error' => "No DeviceDB connection" }
  end
end

#parse_response(response) ⇒ Object



67
68
69
# File 'lib/devicedb_comms/shared.rb', line 67

def parse_response(response)
  JSON.parse(response.body)
end

#post(call, params = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/devicedb_comms/shared.rb', line 43

def post(call, params={})
  if @http
    begin
      parse_response @http.request_post(call + '.json', to_query(params))
    rescue StandardError => e
      { 'error' => "POST failed: #{e.message}" }
    end
  else
    { 'error' => "No DeviceDB connection" }
  end
end

#put(call, params = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/devicedb_comms/shared.rb', line 55

def put(call, params={})
  if @http
    begin
      parse_response @http.request_put(call + '.json', to_query(params))
    rescue StandardError => e
      { 'error' => "PUT failed: #{e.message}" }
    end
  else
    { 'error' => "No DeviceDB connection" }
  end
end

#to_query(params_hash) ⇒ Object



71
72
73
# File 'lib/devicedb_comms/shared.rb', line 71

def to_query(params_hash)
  params_hash.to_query
end