Class: FluentIcons::Cache
- Inherits:
-
Object
- Object
- FluentIcons::Cache
- Defined in:
- lib/fluent-icons/cache.rb
Class Method Summary collapse
-
.cache_dir ⇒ Object
Cache directory in Rails tmp or system tmp.
-
.cache_key(symbol, options = {}) ⇒ Object
Generate cache key from symbol and options.
-
.clear ⇒ Object
Clear all cached files.
-
.fetch(symbol, options = {}) ⇒ Object
Fetch from cache or generate.
-
.read(key) ⇒ Object
Read from file cache.
-
.stats ⇒ Object
Get cache statistics.
-
.write(key, content) ⇒ Object
Write to file cache.
Class Method Details
.cache_dir ⇒ Object
Cache directory in Rails tmp or system tmp
10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/fluent-icons/cache.rb', line 10 def cache_dir @cache_dir ||= begin dir = if defined?(Rails) Rails.root.join('tmp', 'cache', 'fluent-icons') else File.join(Dir.tmpdir, 'fluent-icons-cache') end FileUtils.mkdir_p(dir) dir.to_s end end |
.cache_key(symbol, options = {}) ⇒ Object
Generate cache key from symbol and options
23 24 25 26 27 |
# File 'lib/fluent-icons/cache.rb', line 23 def cache_key(symbol, = {}) = .sort.to_h content = "#{symbol}:#{.inspect}" Digest::MD5.hexdigest(content) end |
.clear ⇒ Object
Clear all cached files
69 70 71 72 73 |
# File 'lib/fluent-icons/cache.rb', line 69 def clear return unless Dir.exist?(cache_dir) FileUtils.rm_rf(Dir.glob(File.join(cache_dir, '*.html'))) end |
.fetch(symbol, options = {}) ⇒ Object
Fetch from cache or generate
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/fluent-icons/cache.rb', line 56 def fetch(symbol, = {}) key = cache_key(symbol, ) cached = read(key) return cached if cached # Generate new content content = yield if block_given? write(key, content) if content content end |
.read(key) ⇒ Object
Read from file cache
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/fluent-icons/cache.rb', line 30 def read(key) file_path = File.join(cache_dir, "#{key}.html") return nil unless File.exist?(file_path) # Check if cache is stale (older than 1 hour) if File.mtime(file_path) < Time.now - 3600 File.delete(file_path) return nil end File.read(file_path) rescue StandardError => e # Silently fail and regenerate nil end |
.stats ⇒ Object
Get cache statistics
76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/fluent-icons/cache.rb', line 76 def stats return { size: 0, files: 0 } unless Dir.exist?(cache_dir) files = Dir.glob(File.join(cache_dir, '*.html')) size = files.sum { |f| File.size(f) } { files: files.count, size: size, size_human: human_size(size), directory: cache_dir } end |
.write(key, content) ⇒ Object
Write to file cache
47 48 49 50 51 52 53 |
# File 'lib/fluent-icons/cache.rb', line 47 def write(key, content) file_path = File.join(cache_dir, "#{key}.html") File.write(file_path, content) rescue StandardError => e # Silently fail - caching is optional nil end |