Class: Filestorage::Local

Inherits:
Object
  • Object
show all
Defined in:
lib/filestorage/local.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_dir) ⇒ Local

Returns a new instance of Local.



12
13
14
# File 'lib/filestorage/local.rb', line 12

def initialize(base_dir)
  @base_dir = Pathname.new(base_dir)
end

Instance Method Details

#delete(path, delete_dir: false) ⇒ Object

Raises:



40
41
42
43
44
45
46
# File 'lib/filestorage/local.rb', line 40

def delete(path, delete_dir: false)
  fullpath = @base_dir + path
  raise NotExist.new("Not exist #{path}") unless File.exist?(fullpath)
  FileUtils.rm(fullpath)
  sweep(fullpath.parent) if delete_dir
  path
end

#exist?(path) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
51
# File 'lib/filestorage/local.rb', line 48

def exist?(path)
  fullpath = @base_dir + path
  File.exist?(fullpath)
end

#filesObject



53
54
55
56
57
58
59
60
# File 'lib/filestorage/local.rb', line 53

def files
  files = []
  Find.find(@base_dir.to_s) do |f|
    f = Pathname.new(f)
    files << f.relative_path_from(@base_dir).to_s if f.file?
  end
  files
end

#get(path) ⇒ Object

Raises:



34
35
36
37
38
# File 'lib/filestorage/local.rb', line 34

def get(path)
  fullpath = @base_dir + path
  raise NotExist.new("Not exist #{path}") unless File.exist?(fullpath)
  File.open(fullpath, "rb")
end

#store(path, file) ⇒ Object

Raises:



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/filestorage/local.rb', line 16

def store(path, file)
  fullpath = @base_dir + path
  raise AlreadyExist.new("Already exist #{path}") if File.exist?(fullpath)
  FileUtils.mkdir_p(fullpath.parent)
  if file.instance_of?(Pathname)
    FileUtils.cp(file, fullpath)
  elsif file.instance_of?(File)
    File.open(fullpath, "wb") do |f|
      f.write(file.read)
    end
  else
    File.open(fullpath, "wb") do |f|
      f.write(file)
    end
  end
  path
end