Class: MotionBlender::Analyzer::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/motion_blender/analyzer/cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Cache

Returns a new instance of Cache.



7
8
9
# File 'lib/motion_blender/analyzer/cache.rb', line 7

def initialize file
  @file = Pathname.new(file)
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



4
5
6
# File 'lib/motion_blender/analyzer/cache.rb', line 4

def file
  @file
end

#hitObject (readonly) Also known as: hit?

Returns the value of attribute hit.



4
5
6
# File 'lib/motion_blender/analyzer/cache.rb', line 4

def hit
  @hit
end

Instance Method Details

#cache_fileObject



52
53
54
55
56
57
58
59
# File 'lib/motion_blender/analyzer/cache.rb', line 52

def cache_file
  @cache_file ||=
    begin
      path = @file
      path = path.relative_path_from(Pathname.new('/')) if path.absolute?
      dir.join(path.to_s + '.yml')
    end
end

#deleteObject



44
45
46
# File 'lib/motion_blender/analyzer/cache.rb', line 44

def delete
  cache_file.exist? && cache_file.delete
end

#dirObject



11
12
13
# File 'lib/motion_blender/analyzer/cache.rb', line 11

def dir
  MotionBlender.config.cache_dir
end

#fetchObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/motion_blender/analyzer/cache.rb', line 15

def fetch
  return yield unless dir

  @hit = valid?
  if @hit
    read
  else
    content = yield
    write content
  end
rescue YAML::Exception
  retry if delete
  raise
end

#readObject



30
31
32
# File 'lib/motion_blender/analyzer/cache.rb', line 30

def read
  YAML.load_file cache_file
end

#valid?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/motion_blender/analyzer/cache.rb', line 48

def valid?
  cache_file.file? && @file.mtime < cache_file.mtime
end

#write(content) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/motion_blender/analyzer/cache.rb', line 34

def write content
  if content.nil?
    delete
  else
    cache_file.dirname.mkpath
    cache_file.write YAML.dump(content)
  end
  content
end