Class: Prefatory::Repository

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

Overview

A repository that temporarily saves ruby objects to a key value store (Redis or Memcached).

Constant Summary collapse

KEY_NOT_FOUND_MSG =
"Unable to find the object with key ?"

Instance Method Summary collapse

Constructor Details

#initialize(key_prefix: nil, storage: nil, config: Prefatory.config) ⇒ Repository

Returns a new instance of Repository.



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

def initialize(key_prefix: nil, storage: nil,
               config: Prefatory.config)
  @config = config
  @storage = storage || Storage::Discover.new(@config.storage, @config.ttl).instance
end

Instance Method Details

#delete(key) ⇒ Object



58
59
60
61
62
# File 'lib/prefatory.rb', line 58

def delete(key)
  return false unless @storage.key?(key)
  @storage.delete(key)
  true
end

#delete!(key) ⇒ Object

Raises:



64
65
66
67
# File 'lib/prefatory.rb', line 64

def delete!(key)
  raise Errors::NotFound, KEY_NOT_FOUND_MSG.sub('?',key) unless @storage.key?(key)
  delete(key)
end

#find(key) ⇒ Object



17
18
19
20
# File 'lib/prefatory.rb', line 17

def find(key)
  return nil unless @storage.key?(key)
  @storage.get(key)
end

#find!(key) ⇒ Object

Raises:



22
23
24
25
26
# File 'lib/prefatory.rb', line 22

def find!(key)
  raise Errors::NotFound, KEY_NOT_FOUND_MSG.sub('?',key) unless @storage.key?(key)
  obj = find(key)
  obj
end

#save(obj, ttl = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/prefatory.rb', line 28

def save(obj, ttl=nil)
  begin
    key = @storage.next_key(obj)
    @storage.set(key, obj, ttl)
  rescue StandardError => e
    logger.info("An error occurred (#{e.inspect}) storing object: #{obj.inspect}")
    key = nil
  end
  key
end

#save!(obj, ttl = nil) ⇒ Object

Raises:



39
40
41
42
43
44
# File 'lib/prefatory.rb', line 39

def save!(obj, ttl=nil)
  key = save(obj, ttl)
  raise Errors::NotSaved,
        "Unable to save object! #{obj.inspect}. Check the log for more information." unless @storage.key?(key)
  key
end

#update(key, obj, ttl = nil) ⇒ Object



46
47
48
49
50
# File 'lib/prefatory.rb', line 46

def update(key, obj, ttl=nil)
  return false unless @storage.key?(key)
  @storage.set(key, obj, ttl)
  true
end

#update!(key, obj, ttl = nil) ⇒ Object

Raises:



52
53
54
55
56
# File 'lib/prefatory.rb', line 52

def update!(key, obj, ttl=nil)
  raise Errors::NotFound, KEY_NOT_FOUND_MSG.sub('?',key) unless @storage.key?(key)

  update(key, obj, ttl)
end