Class: Cocainum::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/cocainum/storage.rb

Instance Method Summary collapse

Constructor Details

#initializeStorage

Returns a new instance of Storage.



7
8
9
# File 'lib/cocainum/storage.rb', line 7

def initialize
  @storage = Cocaine::Synchrony::Service.new('storage')
end

Instance Method Details

#find(namespace, tags) ⇒ Object



65
66
67
68
69
70
71
72
# File 'lib/cocainum/storage.rb', line 65

def find(namespace, tags)
  results = @storage.find(namespace, tags_prepare(tags)).collect
  if results.size > 0 && !results[0].empty?
    results[0]
  else
    []
  end
end

#read(namespace, key) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/cocainum/storage.rb', line 21

def read(namespace, key)
  results = @storage.read(namespace, key).collect
  if results.size > 0 && !results[0].empty?
    results[0]
  else
    ''
  end
end

#read_all(namespace, keys, json = true) ⇒ Object



39
40
41
42
43
# File 'lib/cocainum/storage.rb', line 39

def read_all(namespace, keys, json = true)
  return [] unless keys.class == Array

  keys.map! { |key| (json ? read_json(namespace,key) : read(namespace,key) ) }
end

#read_json(namespace, key) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/cocainum/storage.rb', line 30

def read_json(namespace, key)
  results = read(namespace, key)
  if results.empty?
    {}
  else
    JSON.parse(results, {symbolize_names: true})
  end
end

#remove(namespace, key) ⇒ Object



83
84
85
86
87
# File 'lib/cocainum/storage.rb', line 83

def remove(namespace, key)
  @storage.remove(namespace, key).collect

  true
end

#set_tags(obj, tag_list) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/cocainum/storage.rb', line 55

def set_tags(obj, tag_list)

  tags = []
  if tag_list.class == Array && obj.class == Hash
    tag_list.each {|tag| tags.push tag.to_s + '_' + obj[tag.to_sym].to_s }
  end

  tags
end

#tags_prepare(tags) ⇒ Object



74
75
76
77
78
79
80
81
# File 'lib/cocainum/storage.rb', line 74

def tags_prepare tags
  tags.map! do |tag|
    tag.gsub!(/[^a-z0-9]/i, '_') unless tag == '*'
    tag
  end if tags.class == Array

  tags
end

#update(namespace, key, data, tags_list = []) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/cocainum/storage.rb', line 45

def update(namespace, key, data, tags_list = [])
  if data.class == Hash
    obj = read_json namespace, key

    data.each { |k, value| obj[k.to_sym] = value }

    write_json namespace, key, obj, set_tags(obj, tags_list)
  end
end

#write(namespace, key, value, tags = []) ⇒ Object



11
12
13
14
15
# File 'lib/cocainum/storage.rb', line 11

def write(namespace, key, value, tags = [])
  @storage.write(namespace, key, value, tags_prepare(tags)).collect

  true
end

#write_json(namespace, key, value, tags = []) ⇒ Object



17
18
19
# File 'lib/cocainum/storage.rb', line 17

def write_json(namespace, key, value, tags = [])
  write(namespace, key, JSON.generate(value), ['_ct_json'] + tags_prepare(tags))
end