Class: Cache::YAMLCacheInterceptor

Inherits:
Object
  • Object
show all
Defined in:
lib/jiji/util/cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(range, cache_file_prefix, &block) ⇒ YAMLCacheInterceptor

Returns a new instance of YAMLCacheInterceptor.



10
11
12
13
14
15
# File 'lib/jiji/util/cache.rb', line 10

def initialize( range, cache_file_prefix, &block)
  @name = "cache"
  @range = range
  @cache_file_prefix = cache_file_prefix
  @block = block
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



39
40
41
# File 'lib/jiji/util/cache.rb', line 39

def name
  @name
end

Instance Method Details

#invoke(mi) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/jiji/util/cache.rb', line 16

def invoke( mi )
  cache_file =  @cache_file_prefix + "_" +  mi.name.to_s
  cache_file += "_" + @block.call(mi.name,*mi.arguments) if @block != nil
  cache_file += ".yaml"

  flock = FileLock.new(cache_file + ".lock")
  current = Time.new

  res = nil
  flock.writelock(){
    # キャッシュがあればキャッシュから読む
    if ( File.exist?(cache_file) && current.to_i < (File.mtime(cache_file).to_i + @range) )
      res = YAML.load_file cache_file
    else
      res =  mi.proceed
      File.open( cache_file, "w" ) { |f|
        f.write( YAML.dump(res) )
      }
      File.utime(current, current, cache_file)
    end
  }
  return res
end