Class: CacheIfSlow
- Inherits:
-
Object
- Object
- CacheIfSlow
- Defined in:
- lib/cache_if_slow.rb,
lib/cache_if_slow/version.rb
Constant Summary collapse
- VERSION =
"0.0.2"
Instance Attribute Summary collapse
-
#logger ⇒ Object
Returns the value of attribute logger.
Class Method Summary collapse
Instance Method Summary collapse
- #fetch(name, max_seconds: nil, **options) ⇒ Object
-
#initialize(cache: Rails.cache, expiry_lookup: nil, logger: Rails.logger) ⇒ CacheIfSlow
constructor
A new instance of CacheIfSlow.
Constructor Details
#initialize(cache: Rails.cache, expiry_lookup: nil, logger: Rails.logger) ⇒ CacheIfSlow
Returns a new instance of CacheIfSlow.
8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/cache_if_slow.rb', line 8 def initialize(cache: Rails.cache, expiry_lookup: nil, logger: Rails.logger) @cache = cache @logger = logger if expiry_lookup.present? expiry_lookup.each do |v| raise ArgumentError, "`slower_than` if required for all entries in `expiry_lookup`" if v[:slower_than].blank? raise ArgumentError, "`expires_in` if required for all entries in `expiry_lookup`" if v[:expires_in].blank? end @expiry_lookup = expiry_lookup.sort_by { |v| -v[:slower_than] } end end |
Instance Attribute Details
#logger ⇒ Object
Returns the value of attribute logger.
7 8 9 |
# File 'lib/cache_if_slow.rb', line 7 def logger @logger end |
Class Method Details
.fetch(name, max_seconds:, **options, &block) ⇒ Object
47 48 49 |
# File 'lib/cache_if_slow.rb', line 47 def fetch(name, max_seconds:, **, &block) new.fetch(name, max_seconds: max_seconds, **, &block) end |
Instance Method Details
#fetch(name, max_seconds: nil, **options) ⇒ Object
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 |
# File 'lib/cache_if_slow.rb', line 20 def fetch(name, max_seconds: nil, **) unless block_given? raise ArgumentError, "Missing block: Calling `CacheIfSlow#fetch` requires a block." end if @expiry_lookup.blank? && max_seconds.nil? raise ArgumentError, "`max_seconds` is required if `expiry_lookup` is not present." end max_seconds = @expiry_lookup[-1][:slower_than] if max_seconds.nil? || @expiry_lookup[-1][:slower_than] < max_seconds value = @cache.read(name, ) return value unless value.nil? start = Time.now value = yield(name) total_time = Time.now - start if total_time > max_seconds && @cache.read(name, ).nil? expires_in = lookup_expiry(total_time, ) [:expires_in] = expires_in @logger.info "CacheIfSlow :: Storing '#{name}' as #{total_time} > #{max_seconds} expires_in: #{expires_in}" @cache.write(name, value, ) end value end |