Class: Clook::Consul
- Inherits:
-
Object
- Object
- Clook::Consul
- Defined in:
- lib/clook/consul.rb
Constant Summary collapse
- DEFAULT_HEADERS =
{ "Content-Type" => "application/json", "Accept" => "application/json", }
Class Method Summary collapse
- .fetch(stuff) ⇒ Object
- .find_value(hash) ⇒ Object
- .flat_hash(input) ⇒ Object
- .initialize(consul = "http://192.168.59.103:8500") ⇒ Object
- .merge(array) ⇒ Object
- .parse(data) ⇒ Object
- .squeeze_array(ary) ⇒ Object
Class Method Details
.fetch(stuff) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/clook/consul.rb', line 23 def fetch(stuff) uri = URI.parse(@consul) http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Get.new("/v1/kv/#{stuff}?recurse") DEFAULT_HEADERS.each do |key, value| request.add_field(key, value) end response = http.request(request) if response.body && (response.content_type || '').include?("json") data = JSON.parse(response.body) end parse(data) unless data.nil? end |
.find_value(hash) ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/clook/consul.rb', line 75 def find_value(hash) result = nil hash.each do |key, value| if hash[key].is_a? Hash result = find_value(value) else result = value end end result end |
.flat_hash(input) ⇒ Object
87 88 89 90 91 92 93 |
# File 'lib/clook/consul.rb', line 87 def flat_hash(input) Hash[*input.map { |key, value| value.is_a?(Hash) ? make_hash_one_dimensional(value).map { |nested_key, nested_value| ["#{key}/#{nested_key}",nested_value] } : [key, value] }.flatten] end |
.initialize(consul = "http://192.168.59.103:8500") ⇒ Object
19 20 21 |
# File 'lib/clook/consul.rb', line 19 def initialize(consul="http://192.168.59.103:8500") @consul ||= consul end |
.merge(array) ⇒ Object
54 55 56 |
# File 'lib/clook/consul.rb', line 54 def merge(array) array.group_by(&:keys).map{ |k, v| { k.first => v.flat_map(&:values).reduce(&:merge) } }.reduce(&:merge) end |
.parse(data) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/clook/consul.rb', line 41 def parse(data) results = Array.new data.map do |item| if item["Value"] value = Base64.decode64(item["Value"]) results << (item["Key"].split('/').reverse.reduce(value){ |r, e| {e.to_sym => r} }) end end values = squeeze_array(results) results.count == 1 ? find_value(values) : values end |
.squeeze_array(ary) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/clook/consul.rb', line 58 def squeeze_array(ary) ary .group_by(&:keys) .map do |k, v| flatten_values = v.flat_map(&:values) {}.tap do |h| h[k.first] = if flatten_values[0].is_a?(Hash) squeeze_array(flatten_values) else flatten_values[0] end end end .reduce(&:merge) end |