Class: EtcdDiscovery::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/etcd-discovery/service.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arg) ⇒ Service

Returns a new instance of Service.



8
9
10
11
12
13
14
15
16
# File 'lib/etcd-discovery/service.rb', line 8

def initialize(arg)
  if arg.is_a? Etcd::Node
    @attributes = JSON.parse arg.value
  elsif arg.is_a? Hash
    @attributes = arg
  else
    raise TypeError, "requires a Etcd::Node or a Hash, not a #{arg.class}"
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



6
7
8
# File 'lib/etcd-discovery/service.rb', line 6

def attributes
  @attributes
end

Class Method Details

.get(service) ⇒ Object

Raises:

  • (TypeError)


18
19
20
21
22
23
24
25
26
27
28
# File 'lib/etcd-discovery/service.rb', line 18

def self.get(service)
  raise TypeError, "service should be a String, is a #{service.class}" unless service.is_a? String

  client = EtcdDiscovery.config.client
  begin
    service = client.get("/services_infos/#{service}")
    new service.node
  rescue Etcd::KeyNotFound
    new("name" => service)
  end
end

Instance Method Details

#allObject

Raises:



30
31
32
33
34
35
36
37
38
39
# File 'lib/etcd-discovery/service.rb', line 30

def all
  client = EtcdDiscovery.config.client
  begin
    node = client.get("/services/#{attributes["name"]}", recursive: true).node
  rescue Etcd::KeyNotFound
    raise ServiceNotFound, attributes["name"]
  end
  raise ServiceNotFound, attributes["name"] if node.children.empty?
  node.children.map { |c| Host.new(c) }
end

#oneObject



41
42
43
# File 'lib/etcd-discovery/service.rb', line 41

def one
  all.sample
end

#set_credentials(user, password) ⇒ Object



68
69
70
71
# File 'lib/etcd-discovery/service.rb', line 68

def set_credentials(user, password)
  @attributes["user"] = user
  @attributes["password"] = password
end

#to_jsonObject



64
65
66
# File 'lib/etcd-discovery/service.rb', line 64

def to_json
  attributes.to_json
end

#to_sObject



60
61
62
# File 'lib/etcd-discovery/service.rb', line 60

def to_s
  to_uri.to_s
end

#to_uri(schemes = ["https", "http"]) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/etcd-discovery/service.rb', line 45

def to_uri(schemes = ["https", "http"])
  a = attributes
  return one.to_uri(schemes) unless a["public"]

  schemes = [schemes] if !schemes.is_a?(Array)
  scheme = schemes.reject do |s|
    a["ports"][s].nil?
  end.first
  if a["user"].nil? || a["user"] == ""
    URI("#{scheme}://#{a["hostname"]}:#{a["ports"][scheme]}")
  else
    URI("#{scheme}://#{a["user"]}:#{a["password"]}@#{a["hostname"]}:#{a["ports"][scheme]}")
  end
end