Class: Kubo::BaseFile

Inherits:
Object
  • Object
show all
Defined in:
lib/kubo/base_file.rb

Overview

Base file class

Direct Known Subclasses

Zip

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(time = "1h", path = "./cache") ⇒ BaseFile

Returns a new instance of BaseFile.



8
9
10
11
12
# File 'lib/kubo/base_file.rb', line 8

def initialize(time = "1h", path = "./cache")
  @time = parse_time(time)
  @path = parse_path(path)
  generate_path
end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



6
7
8
# File 'lib/kubo/base_file.rb', line 6

def path
  @path
end

#timeObject

Returns the value of attribute time.



6
7
8
# File 'lib/kubo/base_file.rb', line 6

def time
  @time
end

Instance Method Details

#delete(key) ⇒ Object



41
42
43
44
# File 'lib/kubo/base_file.rb', line 41

def delete(key)
  path = get_file_path(key)
  File.delete(path)
end

#delete_if_expired(key) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/kubo/base_file.rb', line 33

def delete_if_expired(key)
  return false unless file_empty?(key) || file_exists(key)

  delete(key) if expired?(key)

  true
end

#expired?(key) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
# File 'lib/kubo/base_file.rb', line 28

def expired?(key)
  path = get_file_path(key)
  (Time.now - File.mtime(path)) >= @time
end

#file_empty?(key) ⇒ Boolean

Check whether the files is empty or not

Returns:

  • (Boolean)


52
53
54
55
# File 'lib/kubo/base_file.rb', line 52

def file_empty?(key)
  path = get_file_path(key)
  File.size(path)
end

#file_exists?(key) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
60
61
62
63
# File 'lib/kubo/base_file.rb', line 57

def file_exists?(key)
  path = get_file_path(key)

  return false unless File.exist?(path)

  true
end

#flush(key) ⇒ Object



46
47
48
49
# File 'lib/kubo/base_file.rb', line 46

def flush(key)
  path = get_file_path(key)
  File.truncate(path, 0)
end

#get_file_path(key) ⇒ Object

Concatenate absolute path with key



66
67
68
# File 'lib/kubo/base_file.rb', line 66

def get_file_path(key)
  "#{@path}/#{key}"
end

#parse_path(path) ⇒ Object



14
15
16
# File 'lib/kubo/base_file.rb', line 14

def parse_path(path)
  File.expand_path(path)
end

#parse_time(time) ⇒ Object

Convert given time to seconds

Raises:

  • (StandardError)


19
20
21
22
23
24
25
26
# File 'lib/kubo/base_file.rb', line 19

def parse_time(time)
  duration_time = time[...-1].to_i

  raise(StandardError, "Expiration time has to be greater than zero") if duration_time <= 0

  duration_type = time[-1..]
  convert_to_seconds(duration_type, duration_time)
end