Class: Factbase::CachedQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/factbase/cached/cached_query.rb

Overview

Query with a cache, a decorator of another query.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024-2025 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(origin, cache, fb) ⇒ CachedQuery

Constructor.



18
19
20
21
22
# File 'lib/factbase/cached/cached_query.rb', line 18

def initialize(origin, cache, fb)
  @origin = origin
  @cache = cache
  @fb = fb
end

Instance Method Details

#delete!(fb = @fb) ⇒ Integer

Delete all facts that match the query.



60
61
62
63
# File 'lib/factbase/cached/cached_query.rb', line 60

def delete!(fb = @fb)
  @cache.clear
  @origin.delete!(fb)
end

#each(fb = @fb, params = {}) {|Fact| ... } ⇒ Integer

Iterate facts one by one.

Yields:

  • (Fact)

    Facts one-by-one



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/factbase/cached/cached_query.rb', line 34

def each(fb = @fb, params = {})
  return to_enum(__method__, fb, params) unless block_given?
  key = "each #{@origin}" # params are ignored!
  before = @cache[key]
  @cache[key] = @origin.each(fb, params).to_a if before.nil?
  c = 0
  @cache[key].each do |f|
    c += 1
    yield Factbase::CachedFact.new(f, @cache)
  end
  c
end

#one(fb = @fb, params = {}) ⇒ Object

Read a single value.



51
52
53
54
55
56
# File 'lib/factbase/cached/cached_query.rb', line 51

def one(fb = @fb, params = {})
  key = "one: #{@origin} #{params}"
  before = @cache[key]
  @cache[key] = @origin.one(fb, params) if before.nil?
  @cache[key]
end

#to_sString

Print it as a string.



26
27
28
# File 'lib/factbase/cached/cached_query.rb', line 26

def to_s
  @origin.to_s
end