Class: MethodCache
- Inherits:
-
Object
show all
- Defined in:
- lib/methodcache.rb
Defined Under Namespace
Modules: ModuleExtensions
Instance Method Summary
collapse
Constructor Details
#initialize(obj, name, type, options) ⇒ MethodCache
Returns a new instance of MethodCache.
4
5
6
7
8
9
10
11
12
13
14
|
# File 'lib/methodcache.rb', line 4
def initialize obj, name, type, options
@name = name
@type = type
@timestamps = {}
@values = {}
@last_clean = Time.now
@clean_every = options[:clean_every] || 10*60
@duration = options[:for] || 60
@warn_time = options[:warn_time] || 0.03
@umeth = obj.instance_method(name)
end
|
Instance Method Details
#clean? ⇒ Boolean
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/methodcache.rb', line 38
def clean?
expiry = Time.now - @duration
return unless @last_clean < Time.now - @clean_every
@timestamps.keys.each do |key|
next unless @timestamps[key] < expiry
@timestamps.delete(key)
@values.delete(key)
end
@last_clean = Time.now
end
|
#compute?(key, obj, *params) ⇒ Boolean
28
29
30
31
32
33
34
35
36
|
# File 'lib/methodcache.rb', line 28
def compute?(key, obj, *params)
ts = @timestamps[key]
return unless !ts or ts <= Time.now - @duration
timebox "#{@name}(#{key}) was not cached #{ts} < #{Time.now - @duration}", @warn_time do
@values[key] = @umeth.bind(obj).call(*params)
@timestamps[key] = Time.now
end
true
end
|
#timebox(title, max_t = 0.01) ⇒ Object
16
17
18
19
20
21
|
# File 'lib/methodcache.rb', line 16
def timebox title, max_t = 0.01
result = nil
t = Benchmark.realtime{ result = yield }
warn "#{title}: #{(t*1000).to_i}ms" unless t < max_t
result
end
|
#to_proc ⇒ Object
23
24
25
26
|
# File 'lib/methodcache.rb', line 23
def to_proc
cache = self
proc{ |*params| cache.try(self, *params) }
end
|
#try(obj, *params) ⇒ Object
49
50
51
52
53
|
# File 'lib/methodcache.rb', line 49
def try(obj, *params)
key = (@type == :instance ? params + [obj.id] : params).hash
compute?(key, obj, *params) and clean?
@values[key]
end
|