Class: Defile::Backend::FileSystem

Inherits:
Object
  • Object
show all
Defined in:
lib/defile/backend/file_system.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(directory, max_size: nil, hasher: Defile::RandomHasher.new) ⇒ FileSystem

Returns a new instance of FileSystem.



6
7
8
9
10
11
12
# File 'lib/defile/backend/file_system.rb', line 6

def initialize(directory, max_size: nil, hasher: Defile::RandomHasher.new)
  @hasher = hasher
  @directory = directory
  @max_size = max_size

  FileUtils.mkdir_p(@directory)
end

Instance Attribute Details

#directoryObject (readonly)

Returns the value of attribute directory.



4
5
6
# File 'lib/defile/backend/file_system.rb', line 4

def directory
  @directory
end

Instance Method Details

#clear!(confirm = nil) ⇒ Object

Raises:

  • (ArgumentError)


59
60
61
62
63
# File 'lib/defile/backend/file_system.rb', line 59

def clear!(confirm = nil)
  raise ArgumentError, "are you sure? this will remove all files in the backend, call as `clear!(:confirm)` if you're sure you want to do this" unless confirm == :confirm
  FileUtils.rm_rf(@directory)
  FileUtils.mkdir_p(@directory)
end

#delete(id) ⇒ Object



39
40
41
# File 'lib/defile/backend/file_system.rb', line 39

def delete(id)
  FileUtils.rm(path(id)) if exists?(id)
end

#exists?(id) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/defile/backend/file_system.rb', line 55

def exists?(id)
  ::File.exists?(path(id))
end

#get(id) ⇒ Object



35
36
37
# File 'lib/defile/backend/file_system.rb', line 35

def get(id)
  Defile::File.new(self, id)
end

#open(id) ⇒ Object



43
44
45
# File 'lib/defile/backend/file_system.rb', line 43

def open(id)
  ::File.open(path(id), "rb")
end

#path(id) ⇒ Object



65
66
67
# File 'lib/defile/backend/file_system.rb', line 65

def path(id)
  ::File.join(@directory, id)
end

#read(id) ⇒ Object



47
48
49
# File 'lib/defile/backend/file_system.rb', line 47

def read(id)
  ::File.read(path(id)) if exists?(id)
end

#size(id) ⇒ Object



51
52
53
# File 'lib/defile/backend/file_system.rb', line 51

def size(id)
  ::File.size(path(id)) if exists?(id)
end

#upload(uploadable) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/defile/backend/file_system.rb', line 14

def upload(uploadable)
  Defile.verify_uploadable(uploadable, @max_size)

  id = @hasher.hash(uploadable)

  if uploadable.respond_to?(:path) and ::File.exist?(uploadable.path)
    FileUtils.cp(uploadable.path, path(id))
  else
    ::File.open(path(id), "wb") do |file|
      buffer = "" # reuse the same buffer
      until uploadable.eof?
        uploadable.read(Defile.read_chunk_size, buffer)
        file.write(buffer)
      end
      uploadable.close
    end
  end

  Defile::File.new(self, id)
end