Class: AppCache

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

Overview

Provides a common interface for caching and accessing cached cookbook data

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cookbook_path, cache_file = nil) ⇒ AppCache

Returns a new instance of AppCache.



9
10
11
12
# File 'lib/chef_cached_app_info.rb', line 9

def initialize(cookbook_path, cache_file = nil)
  @cookbook_path = cookbook_path
  @cache_file = cache_file.nil? ? 'files/default/app_cache/chef_cached_app_info.json' : cache_file
end

Class Method Details

.for(cookbook_path, cache_file = nil) ⇒ Object



5
6
7
# File 'lib/chef_cached_app_info.rb', line 5

def self.for(cookbook_path, cache_file = nil)
  AppCache.new(cookbook_path, cache_file)
end

Instance Method Details

#cache_versions(origin_file) ⇒ Object



14
15
16
17
# File 'lib/chef_cached_app_info.rb', line 14

def cache_versions(origin_file)
  cached_app_info('app_version', origin_file)
  cached_app_info('cookbook_version', origin_file, ->(x) { x.gsub(/[^0-9.]/i, '') })
end

#cached_app_info(key, origin_file = nil, content_lambda = ->(x) { x }) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/chef_cached_app_info.rb', line 19

def cached_app_info(key, origin_file = nil, content_lambda = ->(x) { x })
  # Cache the original piece of info generated when building the app, so we have it when the app & infra are separated.
  write_info(key, content_lambda.call(IO.read(origin_file).strip)) if !origin_file.nil? && File.exist?(origin_file)
  # Cached version must always exist
  value = cached_app_info_object[key]
  raise "The cached app information stored by #{key} could not be found." if value.nil?
  value
end

#cached_app_info_fileObject



28
29
30
31
32
# File 'lib/chef_cached_app_info.rb', line 28

def cached_app_info_file
  info_file = File.join(@cookbook_path, @cache_file)
  IO.write(info_file, '{}') unless File.exist?(info_file)
  info_file
end

#cached_app_info_objectObject



34
35
36
# File 'lib/chef_cached_app_info.rb', line 34

def cached_app_info_object
  JSON.parse(File.read(cached_app_info_file))
end

#write_info(key, value) ⇒ Object



38
39
40
41
42
# File 'lib/chef_cached_app_info.rb', line 38

def write_info(key, value)
  info = cached_app_info_object
  info[key] = value
  IO.write(cached_app_info_file, info.to_json)
end