Class: Consul::Client::Connection

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

Direct Known Subclasses

OfflineConnection

Instance Method Summary collapse

Instance Method Details

#configObject



7
8
9
# File 'lib/consul/client/connection.rb', line 7

def config
  @config ||= Config.new
end

#decode(value) ⇒ Object



75
76
77
# File 'lib/consul/client/connection.rb', line 75

def decode(value)
  Psych.safe_load(value, [Symbol])
end

#decode_r(data) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/consul/client/connection.rb', line 67

def decode_r(data)
  if data.respond_to?(:keys)
    Hash[ data.map{ |k,v| [k,decode_r(v)] } ]
  else
    decode(data.value)
  end
end

#delete(keypath, opts = {}) ⇒ Object



34
35
36
# File 'lib/consul/client/connection.rb', line 34

def delete(keypath, opts={})
  http.delete("/kv" + path(keypath) + (opts[:recursive] ? '?recurse' : '')).value
end

#encode(value) ⇒ Object



79
80
81
82
83
84
85
# File 'lib/consul/client/connection.rb', line 79

def encode(value)
  encoded = Psych.dump(value)
  if decode(encoded) != value
    raise TypeError, "Unable to relaibly decode #{value.class}"
  end
  encoded
end

#encode_r(data) ⇒ Object



87
88
89
90
91
92
93
# File 'lib/consul/client/connection.rb', line 87

def encode_r(data)
  if data.respond_to?(:keys)
    Hash[ data.map{ |k,v| [k, encode_r(v)] } ]
  else
    encode(data)
  end
end

#httpObject

def has_lock?(keypath)

read("/kv/" + keypath).session == session_id

end



59
60
61
# File 'lib/consul/client/connection.rb', line 59

def http
  @http ||= Consul::Http.new
end

#path(keypath) ⇒ Object



63
64
65
# File 'lib/consul/client/connection.rb', line 63

def path(keypath)
  File.join("/" + config.namespace,  keypath).gsub(%r{//}, '/')
end

#read(keypath, opts = {}) ⇒ Object



21
22
23
24
# File 'lib/consul/client/connection.rb', line 21

def read(keypath, opts={})
  response = read_obj(keypath, opts)
  read_value_r(response)
end

#read_obj(keypath, opts = {}) ⇒ Object



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

def read_obj(keypath, opts={})
  keyname = File.basename(keypath)
  response = http.get("/kv" + path(keypath) + (opts[:recursive] ? '?recurse' : ''))
  if response.length == 1 && response.keys.first == keyname
    response[keyname]
  else
    response
  end
end

#read_value_r(response) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/consul/client/connection.rb', line 26

def read_value_r(response)
  if response.respond_to?(:keys)
    Hash[ response.map{ |k,v| [k,read_value_r(v)] } ]
  else
    response.value
  end
end

#write(keypath, data = nil, path_mimic = false) ⇒ Object



38
39
40
41
# File 'lib/consul/client/connection.rb', line 38

def write(keypath,data=nil,path_mimic=false)
  data = encode(data)
  http.put("/kv" + path(keypath), data)
end