Class: Vibe::File

Inherits:
Object
  • Object
show all
Defined in:
lib/vibe/cache-drivers/file.rb

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir = '') ⇒ File

Returns a new instance of File.



4
5
6
7
8
9
10
11
12
# File 'lib/vibe/cache-drivers/file.rb', line 4

def initialize(cache_dir = '')
  # Cache directory in sys temp path if not
  # explicitly set
  @cache_dir = Dir.tmpdir()+'/vibe_gem/' if cache_dir == ''

  if !Dir.exists?(@cache_dir)
      Dir.mkdir(@cache_dir)
  end
end

Instance Method Details

#file_age(name) ⇒ Int

Return the number of days since the file was last modified

Returns:

  • (Int)


51
52
53
# File 'lib/vibe/cache-drivers/file.rb', line 51

def file_age(name)
  (Time.now - ::File.stat(name).mtime)/(24*3600)
end

#get(key = '') ⇒ Boolean

Get content from cache file. This function would delete cache if expired(Older than a day)

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/vibe/cache-drivers/file.rb', line 18

def get(key = '')
  if key != '' && ::File.exists?(@cache_dir+key)
    # Is the File older than a day?
    if file_age(@cache_dir+key) > 1
      # Delete and return a cache miss
      File.delete(@cache_dir+key)
      return false
    end

    puts "Reading from cache with key: #{key}" if ENV['DEBUG']
    data = ::File.read(@cache_dir+key)
    return (data.length > 0) ? data : false
  end

  return false
end

#put(key = '', data = '') ⇒ Boolean

Write content into cache file

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
# File 'lib/vibe/cache-drivers/file.rb', line 38

def put(key = '', data = '')
  if key != '' && data != ''
    puts "Writing into cache with key: #{key}" if ENV['DEBUG']
    return ::File.write(@cache_dir+key, data)
  end

  return false
end