Module: Flycal::CacheAnnotator
- Defined in:
- lib/flycal/cache_annotator.rb
Overview
Injects cache HIT/MISS metadata into text / JSON payloads.
Class Method Summary collapse
- .annotate_payload!(payload, status, cache_key) ⇒ Object
- .annotate_text(text, status, cache_key = nil) ⇒ Object
- .insert_cache_line!(lines, status, cache_key = nil, fallback: :append) ⇒ Object
- .line(status, _cache_key = nil) ⇒ Object
- .stringify_keys(value) ⇒ Object
- .strip_for_storage(payload) ⇒ Object
Class Method Details
.annotate_payload!(payload, status, cache_key) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/flycal/cache_annotator.rb', line 18 def annotate_payload!(payload, status, cache_key) payload = stringify_keys(payload) info = payload["info"] ||= {} info["cache"] = status info.delete("cache_key") if payload["text"].is_a?(Array) lines = payload["text"].map(&:to_s) insert_cache_line!(lines, status, cache_key, fallback: :unshift) payload["text"] = lines end payload end |
.annotate_text(text, status, cache_key = nil) ⇒ Object
12 13 14 15 16 |
# File 'lib/flycal/cache_annotator.rb', line 12 def annotate_text(text, status, cache_key = nil) lines = text.to_s.sub(/\n\z/, "").split("\n") insert_cache_line!(lines, status, cache_key, fallback: :append) "#{lines.join("\n")}\n" end |
.insert_cache_line!(lines, status, cache_key = nil, fallback: :append) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/flycal/cache_annotator.rb', line 57 def insert_cache_line!(lines, status, cache_key = nil, fallback: :append) lines.reject! { |l| l.to_s.start_with?("Cache:") } marker = line(status, cache_key) occupied_idx = lines.index { |l| l.to_s.start_with?("Total time occupied:") } if occupied_idx lines.insert(occupied_idx + 1, marker) return lines end idx = lines.index("---") if idx lines.insert(idx + 1, marker) else blank_idx = lines.index { |l| l == "" } if blank_idx lines.insert(blank_idx, marker) elsif fallback == :unshift lines.unshift(marker) else lines << "---" << marker end end lines end |
.line(status, _cache_key = nil) ⇒ Object
8 9 10 |
# File 'lib/flycal/cache_annotator.rb', line 8 def line(status, _cache_key = nil) "Cache: #{status}" end |
.stringify_keys(value) ⇒ Object
46 47 48 49 50 51 52 53 54 55 |
# File 'lib/flycal/cache_annotator.rb', line 46 def stringify_keys(value) case value when Hash value.each_with_object({}) { |(k, v), out| out[k.to_s] = stringify_keys(v) } when Array value.map { |v| stringify_keys(v) } else value end end |
.strip_for_storage(payload) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/flycal/cache_annotator.rb', line 33 def strip_for_storage(payload) copy = Marshal.load(Marshal.dump(stringify_keys(payload))) if copy["info"].is_a?(Hash) copy["info"] = copy["info"].dup copy["info"].delete("cache") copy["info"].delete("cache_key") end if copy["text"].is_a?(Array) copy["text"] = copy["text"].reject { |l| l.to_s.start_with?("Cache:") } end copy end |