Class: Ruby::Reports::CacheFile

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby/reports/cache_file.rb

Overview

Class describes how to storage and access cache file NOTE: Every time any cache file is opening,

cache is cleared from old files.

Constant Summary collapse

DEFAULT_EXPIRE_TIME =
86_400
DEFAULT_CODING =
'utf-8'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir, filename, options = {}) ⇒ CacheFile

Returns a new instance of CacheFile.



13
14
15
16
17
18
19
20
21
# File 'lib/ruby/reports/cache_file.rb', line 13

def initialize(dir, filename, options = {})
  @dir = dir
  @filename = File.join(dir, filename)
  @ext = File.extname(@filename)

  # options
  @coding = options[:coding] || DEFAULT_CODING
  @expiration_time = options[:expire_in] || DEFAULT_EXPIRE_TIME
end

Instance Attribute Details

#codingObject (readonly)

Returns the value of attribute coding.



12
13
14
# File 'lib/ruby/reports/cache_file.rb', line 12

def coding
  @coding
end

#dirObject (readonly)

Returns the value of attribute dir.



12
13
14
# File 'lib/ruby/reports/cache_file.rb', line 12

def dir
  @dir
end

#expiration_timeObject (readonly)

Returns the value of attribute expiration_time.



12
13
14
# File 'lib/ruby/reports/cache_file.rb', line 12

def expiration_time
  @expiration_time
end

#extObject (readonly)

Returns the value of attribute ext.



12
13
14
# File 'lib/ruby/reports/cache_file.rb', line 12

def ext
  @ext
end

Instance Method Details

#clearObject



47
48
49
# File 'lib/ruby/reports/cache_file.rb', line 47

def clear
  FileUtils.rm_f(@filename)
end

#exists?Boolean Also known as: ready?

Returns:

  • (Boolean)


23
24
25
# File 'lib/ruby/reports/cache_file.rb', line 23

def exists?
  !expired?(@filename)
end

#filenameObject



28
29
30
31
# File 'lib/ruby/reports/cache_file.rb', line 28

def filename
  fail 'File doesn\'t exist, check exists? before' unless exists?
  @filename
end

#open(force = false) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ruby/reports/cache_file.rb', line 33

def open(force = false)
  prepare_cache_dir

  (force ? clear : return) if File.exists?(@filename)

  with_tempfile do |tempfile|
    yield tempfile

    tempfile.close
    FileUtils.cp(tempfile.path, @filename)
    FileUtils.chmod(0644, @filename)
  end
end