Class: Stonk::Adapter::FileCacheAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/stonk/adapter/file_cache_adapter.rb

Instance Method Summary collapse

Constructor Details

#initialize(cache_file_path, default_ttl: 60 * 60) ⇒ FileCacheAdapter

Returns a new instance of FileCacheAdapter.



9
10
11
12
13
# File 'lib/stonk/adapter/file_cache_adapter.rb', line 9

def initialize(cache_file_path, default_ttl: 60 * 60)
  @cache_file_path = cache_file_path
  @default_ttl = default_ttl
  @data = nil
end

Instance Method Details

#clear_cacheObject



47
48
49
# File 'lib/stonk/adapter/file_cache_adapter.rb', line 47

def clear_cache
  FileUtils.rm_f(cache_path)
end

#clear_expired_entriesObject



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/stonk/adapter/file_cache_adapter.rb', line 51

def clear_expired_entries
  load_data
  original_size = @data.size

  @data.delete_if do |_symbol, entry|
    Time.now.to_i >= entry["expires_at"]
  end

  if @data.size < original_size
    save_data
    Stonk.logger.debug("[FileCacheAdapter] Cleared #{original_size - @data.size} expired entries")
  end
end

#get_stock_price(stock_symbol) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/stonk/adapter/file_cache_adapter.rb', line 15

def get_stock_price(stock_symbol)
  load_data

  raise Stonk::Adapter::StockNotFound, "Stock not found: #{stock_symbol}" unless @data.key?(stock_symbol)

  entry = @data[stock_symbol]

  if Time.now.to_i >= entry["expires_at"]
    @data.delete(stock_symbol)
    save_data
    raise Stonk::Adapter::StockNotFound, "Stock not found: #{stock_symbol}"
  end

  entry["price"]
end

#set_stock_price(stock_symbol, price, ttl: nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/stonk/adapter/file_cache_adapter.rb', line 31

def set_stock_price(stock_symbol, price, ttl: nil)
  return if price.nil?

  load_data

  ttl_seconds = ttl || @default_ttl
  expires_at = Time.now.to_i + ttl_seconds

  @data[stock_symbol] = {
    "price" => price,
    "expires_at" => expires_at,
  }

  save_data
end