1
module Puppet::Util::Cacher
5
# Cause all cached values to be considered expired.
10
# Is the provided timestamp earlier than our expiration timestamp?
11
# If it is, then the associated value is expired.
12
def dependent_data_expired?(ts)
13
return false unless timestamp
21
# Our module has been extended in a class; we can only add the Instance methods,
22
# which become *class* methods in the class.
23
def self.extended(other)
26
include InstanceMethods
30
# Our module has been included in a class, which means the class gets the class methods
31
# and all of its instances get the instance methods.
32
def self.included(other)
33
other.extend(ClassMethods)
34
other.send(:include, InstanceMethods)
37
# Methods that can get added to a class.
39
# Provide a means of defining an attribute whose value will be cached.
40
# Must provide a block capable of defining the value if it's flushed..
41
def cached_attr(name, options = {}, &block)
42
init_method = "init_" + name.to_s
43
define_method(init_method, &block)
45
define_method(name) do
49
define_method(name.to_s + "=") do |value|
50
# Make sure the cache timestamp is set
52
value_cache[name] = value
55
if ttl = options[:ttl]
56
set_attr_ttl(name, ttl)
61
return nil unless defined?(@attr_ttls) and @attr_ttls
65
def set_attr_ttl(name, value)
67
@attr_ttls[name] = Integer(value)
71
# Methods that get added to instances.
72
module InstanceMethods
74
# Only expire if we have an expirer. This is
75
# mostly so that we can comfortably handle cases
76
# like Puppet::Type instances, which use their
77
# catalog as their expirer, and they often don't
91
unless defined?(@cache_timestamp)
92
@cache_timestamp = Time.now
97
def cached_value(name)
98
# Allow a nil expirer, in which case we regenerate the value every time.
99
if expired_by_expirer?(name)
101
@cache_timestamp = Time.now
102
elsif expired_by_ttl?(name)
103
value_cache.delete(name)
105
unless value_cache.include?(name)
106
value_cache[name] = send("init_%s" % name)
111
def expired_by_expirer?(name)
113
return true unless self.class.attr_ttl(name)
115
return expirer.dependent_data_expired?(cache_timestamp)
118
def expired_by_ttl?(name)
119
return false unless self.class.respond_to?(:attr_ttl)
120
return false unless ttl = self.class.attr_ttl(name)
122
@ttl_timestamps ||= {}
123
@ttl_timestamps[name] ||= Time.now
125
return (Time.now - @ttl_timestamps[name]) > ttl
129
unless defined?(@value_cache) and @value_cache