Class: OpenBEL::Storage::CacheProxy

Inherits:
Object
  • Object
show all
Includes:
TripleStorage
Defined in:
lib/openbel/api/storage/cache_proxy.rb

Instance Method Summary collapse

Methods included from TripleStorage

#all, #object, #predicate, #subject

Constructor Details

#initialize(real_storage, cache) ⇒ CacheProxy

Returns a new instance of CacheProxy.



8
9
10
11
12
13
14
15
16
17
# File 'lib/openbel/api/storage/cache_proxy.rb', line 8

def initialize(real_storage, cache)
  if !real_storage or !real_storage.respond_to?(:triples)
    fail ArgumentError, "real_storage is invalid."
  end
  if !cache or !cache.respond_to?(:[])
    fail ArgumentError, "cache is invalid."
  end
  @real_storage = real_storage
  @cache = cache
end

Instance Method Details

#triples(subject, predicate, object, options = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/openbel/api/storage/cache_proxy.rb', line 19

def triples(subject, predicate, object, options={})
  pattern_key = key(subject, predicate, object)
  rdf_value = @cache[pattern_key]
  map_method = options.delete(:only)
  if rdf_value
    return [] if rdf_value == ""
    triples = unpack(rdf_value).each_slice(3)
  else
    triples = @real_storage.triples(subject, predicate, object, options).to_a
    if triples.empty?
      @cache[pattern_key] = ""
    else
      rdf_value = triples.map { |stmt|
        [subject(stmt), predicate(stmt), object(stmt)]
      }.flatten
      @cache[pattern_key] = pack(rdf_value)
    end
    triples
  end

  map_method = if map_method && @real_storage.respond_to?(map_method)
                 @real_storage.method(map_method)
               else
                 @real_storage.method(:all)
               end
  if block_given?
    triples.each { |triple| yield map_method.call(triple) }
  else
    triples = triples.respond_to?(:lazy) ? triples.lazy : triples
    triples.map { |triple| map_method.call(triple) }
  end
end