Class: Eras::Adapters::FileSystem

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/eras/adapters/file_system.rb

Defined Under Namespace

Classes: Error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir = nil) ⇒ FileSystem

Returns a new instance of FileSystem.

Raises:



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/eras/adapters/file_system.rb', line 9

def initialize(dir = nil)
  if dir.nil?
    dir = Rails.root.join("tmp", "eras")

    Dir.mkdir(dir) unless File.exist?(dir)
  end

  raise Error, "Directory #{dir} does not exist" unless File.exist?(dir)

  @path = File.join(dir, "errors.json")
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



7
8
9
# File 'lib/eras/adapters/file_system.rb', line 7

def path
  @path
end

Instance Method Details

#destroy_fileObject



52
53
54
55
# File 'lib/eras/adapters/file_system.rb', line 52

def destroy_file
  return unless File.exist?(@path)
  File.delete(@path)
end

#file_sizeObject



57
58
59
60
# File 'lib/eras/adapters/file_system.rb', line 57

def file_size
  size = File.exist?(@path) ? File.size(@path) : 0
  number_to_human_size(size)
end

#read_error(id) ⇒ Object



48
49
50
# File 'lib/eras/adapters/file_system.rb', line 48

def read_error(id)
  read_errors.find { |e| e['id'] == id }
end

#read_errorsObject



40
41
42
43
44
45
46
# File 'lib/eras/adapters/file_system.rb', line 40

def read_errors
  return [] unless File.exist?(@path)

  File.open(@path, "r") do |f|
    JSON.parse(f.read)
  end
end

#write_error(data) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/eras/adapters/file_system.rb', line 21

def write_error(data)
  # Database adapters may have an id, but filesystem adapters don't
  data['id'] = SecureRandom.uuid

  # TODO: Large numbers of errors will cause this to grow unbounded, could have memory issues.
  # Should we use file rotation, sqlite (separate adapter), or something else?
  existing_errors = begin
    JSON.parse(File.read(@path))
  rescue Errno::ENOENT, JSON::ParserError
    []
  end

  File.open(@path, "w") do |f|
    errors = existing_errors
    errors.unshift(data)
    f.write(errors.to_json)
  end
end