Module: Emojidex::CollectionCache

Included in:
Collection
Defined in:
lib/emojidex/collection/cache.rb

Overview

local caching functionality for collections

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#cache_pathObject (readonly)

Returns the value of attribute cache_path.



8
9
10
# File 'lib/emojidex/collection/cache.rb', line 8

def cache_path
  @cache_path
end

Instance Method Details

#cache!(options = {}) ⇒ Object

Caches emoji to local emoji storage cache Options:

cache_path: manually specify cache location
  (default is ENV['EMOJI_CACHE'] or '$HOME/.emoji_cache')
formats: formats to cache (default is SVG only)
sizes: sizes to cache (default is px32, but this is irrelivant for SVG)


29
30
31
32
33
34
35
36
37
38
# File 'lib/emojidex/collection/cache.rb', line 29

def cache!(options = {})
  setup_cache options[:cache_path]
  formats = options[:formats] || [:svg, :png]
  sizes = options[:sizes] || [:px32]
  @emoji.values.each do |moji|
    _svg_check_copy(moji) if formats.include? :svg
    _raster_check_copy(moji, :png, sizes) if formats.include? :png
  end
  cache_index
end

#cache_index(destination = nil) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/emojidex/collection/cache.rb', line 40

def cache_index(destination = nil)
  destination ||= @cache_path
  idx = Emojidex::Collection.new
  idx.load_local_collection(destination) if FileTest.exist? "#{destination}/emoji.json"
  idx.add_emoji @emoji.values
  File.open("#{destination}/emoji.json", 'w') do |f|
    f.write idx.emoji.values.to_json
  end
end

#setup_cache(path = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/emojidex/collection/cache.rb', line 10

def setup_cache(path = nil)
  # check if cache dir is already set
  return @cache_path if @cache_path && path.nil?
  # setup cache
  @cache_path = File.expand_path(path || ENV['EMOJI_CACHE'] || "#{ENV['HOME']}/.emojidex/cache")
  ENV['EMOJI_CACHE'] = @cache_path
  FileUtils.mkdir_p(@cache_path)
  Emojidex::Defaults.sizes.keys.each do |size|
    FileUtils.mkdir_p(@cache_path + "/#{size}")
  end
  @cache_path
end

#write_index(destination) ⇒ Object



50
51
52
53
54
55
# File 'lib/emojidex/collection/cache.rb', line 50

def write_index(destination)
  idx = @emoji.values.to_json
  idx = JSON.parse idx
  idx.each { |moji| moji.delete_if{ |k, v| v.nil? }}
  File.open("#{destination}/emoji.json", 'w') { |f| f.write idx.to_json }
end