Class: Cosmo::API::KV

Inherits:
Object
  • Object
show all
Defined in:
lib/cosmo/api/kv.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, options = nil) ⇒ KV

Returns a new instance of KV.



6
7
8
9
# File 'lib/cosmo/api/kv.rb', line 6

def initialize(name, options = nil)
  @name = name
  @options = Hash(options)
end

Instance Method Details

#cleanObject



45
46
47
# File 'lib/cosmo/api/kv.rb', line 45

def clean
  Client.instance.purge("KV_#{@name}", ">")
end

#countObject Also known as: size



49
50
51
52
53
# File 'lib/cosmo/api/kv.rb', line 49

def count
  keys.size
rescue NATS::KeyValue::NoKeysFoundError
  0
end

#delete(key) ⇒ Object



21
22
23
# File 'lib/cosmo/api/kv.rb', line 21

def delete(key)
  kv.delete(key)
end

#get(key) ⇒ Object



15
16
17
18
19
# File 'lib/cosmo/api/kv.rb', line 15

def get(key)
  kv.get(key).value
rescue NATS::KeyValue::KeyNotFoundError
  # nop
end

#keys(subject = nil, limit: 25) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/cosmo/api/kv.rb', line 25

def keys(subject = nil, limit: 25)
  results = []
  params = { ignore_deletes: true, meta_only: true }
  watcher = kv.watch(subject || ">", params)

  watcher.each do |entry|
    break unless entry

    results << entry.key
    break if results.size >= limit
  end
  watcher.stop

  results
end

#purge(key) ⇒ Object



41
42
43
# File 'lib/cosmo/api/kv.rb', line 41

def purge(key)
  kv.purge(key)
end

#set(key, value) ⇒ Object



11
12
13
# File 'lib/cosmo/api/kv.rb', line 11

def set(key, value)
  kv.put(key, value.to_s)
end