Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions lib/puppet/functions/extlib/cache_data.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
#
# @example With a random password
# $password = cache_data('mysql', 'mysql_password', random_password())
#
# @example With an expensive initial data
# $password = cache_data('mysql', 'mysql_password') { random_password() }
Puppet::Functions.create_function(:'extlib::cache_data') do
# @param namespace Namespace for the cache
# @param name Cache key within the namespace
Expand All @@ -30,12 +33,35 @@
end

def cache_data(namespace, name, initial_data)
implementation(namespace, name, initial_data)
end

# @param namespace Namespace for the cache
# @param name Cache key within the namespace
# @param initial_data The data for when there is no cache yet
# @return The cached value when it exists. The initial data when no cache exists
dispatch :cache_data do
param 'String[1]', :namespace
param 'String[1]', :name
block_param 'Any', :initial_data
return_type 'Any'
end

def cache_data(namespace, name, &initial_data)
implementation(namespace, name, initial_data)
end

private

def implementation(namespace, name, initial_data)
cache_dir = File.join(Puppet[:vardir], namespace)
cache = File.join(cache_dir, name)

if File.exist? cache
YAML.safe_load(File.read(cache))
else
initial_data = initial_data.call if initial_data.respond_to?(:call)

FileUtils.mkdir_p(cache_dir)
File.open(cache, 'w', 0o600) do |c|
c.write(YAML.dump(initial_data))
Expand Down