Class: Utils::HashCache

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

Instance Method Summary collapse

Constructor Details

#initialize(cache_file) ⇒ HashCache

Returns a new instance of HashCache.



5
6
7
8
# File 'lib/utils/hash_cache.rb', line 5

def initialize(cache_file)
  @cache_file = cache_file
  @all_content = read_all
end

Instance Method Details

#read(key) ⇒ Object



21
22
23
# File 'lib/utils/hash_cache.rb', line 21

def read(key)
  @all_content&.dig(key)
end

#read_allObject



10
11
12
13
14
15
16
17
18
19
# File 'lib/utils/hash_cache.rb', line 10

def read_all
  begin
    file_content = File.read(@cache_file)
    return JSON.parse file_content unless file_content.empty?

    {}
  rescue
    {}
  end
end

#write(data) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/utils/hash_cache.rb', line 25

def write(data)
  item_map = read_all
  File.open(@cache_file, 'w') do |file|
    new_data = { **item_map, **data }

    file.write new_data.to_json
  end
end