Class: Wrappix::Templates::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/wrappix/templates/cache.rb

Class Method Summary collapse

Class Method Details

.render(module_name, _config) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
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
51
52
53
54
55
56
57
58
59
# File 'lib/wrappix/templates/cache.rb', line 6

def self.render(module_name, _config)
  <<~RUBY
    # frozen_string_literal: true

    module #{module_name}
      # Memory cache implementation
      class MemoryCache
        def initialize
          @store = {}
        end

        def read(key)
          @store[key]
        end

        def write(key, value)
          @store[key] = value
        end

        def delete(key)
          @store.delete(key)
        end

        def clear
          @store = {}
        end
      end

      # File cache implementation
      class FileCache
        def initialize(path = "#{module_name.downcase}_cache.yaml")
          require "yaml/store"
          @store = YAML::Store.new(path)
        end

        def read(key)
          @store.transaction(true) { @store[key] }
        end

        def write(key, value)
          @store.transaction { @store[key] = value }
        end

        def delete(key)
          @store.transaction { @store.delete(key) }
        end

        def clear
          @store.transaction { @store.roots.each { |key| @store.delete(key) } }
        end
      end
    end
  RUBY
end