Class: Eras::Adapters::FileSystem
- Inherits:
-
Object
- Object
- Eras::Adapters::FileSystem
- Includes:
- ActionView::Helpers::NumberHelper
- Defined in:
- lib/eras/adapters/file_system.rb
Defined Under Namespace
Classes: Error
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
Instance Method Summary collapse
- #destroy_file ⇒ Object
- #file_size ⇒ Object
-
#initialize(dir = nil) ⇒ FileSystem
constructor
A new instance of FileSystem.
- #read_error(id) ⇒ Object
- #read_errors ⇒ Object
- #write_error(data) ⇒ Object
Constructor Details
#initialize(dir = nil) ⇒ FileSystem
Returns a new instance of FileSystem.
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
#path ⇒ Object (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_file ⇒ Object
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_size ⇒ Object
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_errors ⇒ Object
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 |