Class: HeroiconsHelper::Cache

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

Overview

:nodoc:

Constant Summary collapse

LOOKUP =
{}

Class Method Summary collapse

Class Method Details

.clear!Object



32
33
34
# File 'lib/heroicons_helper/cache.rb', line 32

def clear!
  LOOKUP.clear
end

.get_key(name:, variant:, **attributes) ⇒ Object



9
10
11
12
13
14
# File 'lib/heroicons_helper/cache.rb', line 9

def get_key(name:, variant:, **attributes)
  attrs = { name: name, variant: variant }.merge(attributes)

  attrs.compact!
  attrs.hash
end

.limitObject

Cache size limit.



21
22
23
# File 'lib/heroicons_helper/cache.rb', line 21

def limit
  500
end

.preload!(icons_to_preload, &block) ⇒ Object

Parameters:

  • icons_to_preload (Array<Hash>)

    List of icons to render, in the format { name: :icon_name, variant: “variant” }.

Raises:

  • (ArgumentError)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/heroicons_helper/cache.rb', line 37

def preload!(icons_to_preload, &block)
  raise ArgumentError, "icons_to_preload must be an Array; it's #{icons_to_preload.class}" unless icons_to_preload.is_a?(Array)
  raise ArgumentError, "icons_to_preload must have between 1 and 20 items; you have #{preload.count}" unless (1..20).cover?(icons_to_preload.count)

  icons_to_preload.each do |icon|
    height = icon["height"] || nil
    width = icon["width"] || nil

    # Don't allow sizes under 16px
    if !height.nil? && height.to_i < 16
      height = nil
    end
    if !width.nil? && width.to_i < 16
      width = nil
    end

    cache_key = HeroiconsHelper::Cache.get_key(
      name: icon["name"],
      variant: icon["variant"],
      height: height,
      width: width,
    )

    cache_icon = HeroiconsHelper::Cache.read(cache_key)
    found = !cache_icon.nil?

    result = yield found, cache_icon || icon

    HeroiconsHelper::Cache.set(cache_key, result) unless found
  end
end

.read(key) ⇒ Object



16
17
18
# File 'lib/heroicons_helper/cache.rb', line 16

def read(key)
  LOOKUP[key]
end

.set(key, value) ⇒ Object



25
26
27
28
29
30
# File 'lib/heroicons_helper/cache.rb', line 25

def set(key, value)
  LOOKUP[key] = value

  # Remove first item when the cache is too large.
  LOOKUP.shift if LOOKUP.size > limit
end