Class: Text::Gen::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/text/gen/store.rb

Overview

Store is a local cache of a builder that is persistent per store to save time on database lookups or transformations.

Constant Summary collapse

NOT_FOUND_BUILDER =
{
  "filters" => [],
  "meta" => {},
  "items" => []
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(lookup) ⇒ Store

Returns a new instance of Store.



14
15
16
17
# File 'lib/text/gen/store.rb', line 14

def initialize(lookup)
  @lookup = lookup
  @store = {}
end

Instance Method Details

#add(key, builder) ⇒ Object



23
24
25
26
# File 'lib/text/gen/store.rb', line 23

def add(key, builder)
  @store[key.to_s.downcase] = builder
  builder
end

#clear(key) ⇒ Object



28
29
30
# File 'lib/text/gen/store.rb', line 28

def clear(key)
  @store.delete(key.to_s.downcase)
end

#fetch(key) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/text/gen/store.rb', line 32

def fetch(key)
  builder = find(key)
  return builder if builder

  builder = @lookup.call(key)
  return not_found(key) unless builder

  add(key, builder.merge("key" => key.to_s.downcase))
end

#find(key) ⇒ Object



19
20
21
# File 'lib/text/gen/store.rb', line 19

def find(key)
  @store[key.to_s.downcase]
end

#not_found(key) ⇒ Object



42
43
44
45
46
# File 'lib/text/gen/store.rb', line 42

def not_found(key)
  hsh = NOT_FOUND_BUILDER.dup
  hsh["key"] = key
  hsh
end

#to_hObject



48
49
50
# File 'lib/text/gen/store.rb', line 48

def to_h
  @store
end