Class: EasyCache

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

Overview

This is the core of EasyCache. EasyCache provides an easy-to-use, in-memory cache system for Ruby. It is designed for situations where you don’t want to set up Redis or Memcached but still want a simple solution for caching key-value data.

Instance Method Summary collapse

Constructor Details

#initializeEasyCache

Returns a new instance of EasyCache.



23
24
25
26
# File 'lib/easycache.rb', line 23

def initialize
  @cache = {}
  @mutex = Mutex.new
end

Instance Method Details

#fetch(key, expiration = 3600, store_in_cache = false) ⇒ Object

rubocop:disable Style/OptionalBooleanParameter



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/easycache.rb', line 28

def fetch(key, expiration = 3600, store_in_cache = false) # rubocop:disable Style/OptionalBooleanParameter
  @mutex.synchronize do
    return cached_value(key, store_in_cache) if cache_contains_valid_data?(key) && !block_given?

    if should_fetch_from_block?(key, store_in_cache)
      value = block_given? ? yield : nil
      cache_value(key, value, expiration) if value && store_in_cache
      value
    else
      cached_value(key, store_in_cache)
    end
  end
end