Class: S3aps::FileAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/s3aps/file_adapter.rb

Overview

Reads, writes and lists files on the filesystem.

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ FileAdapter

Options:

  • :path - where the local files are (default is tmp)



9
10
11
# File 'lib/s3aps/file_adapter.rb', line 9

def initialize(options = {})
  @path = options[:path] || "tmp"
end

Instance Method Details

#listObject

List all the files in the path, recursively



14
15
16
17
18
# File 'lib/s3aps/file_adapter.rb', line 14

def list
  Dir.glob("#{@path}/**/*").select{|path| File.file?(path) }.map do |path|
    path.sub Regexp.new("^#{@path}\/"), ''
  end
end

#md5sum(path) ⇒ Object

:nodoc:



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/s3aps/file_adapter.rb', line 42

def md5sum(path) #:nodoc:
  md5 = nil
  begin
    md5 = File.open(File.join(@path, path), 'rb') do |io|
      d = Digest::MD5.new
      s = ""
      d.update(s) while io.read(4096, s)
      d
    end
  rescue
  end
  md5 ? md5.to_s : nil
end

#read(path) ⇒ Object

Read the file.



38
39
40
# File 'lib/s3aps/file_adapter.rb', line 38

def read(path)
  File.open(File.join(@path, path),"rb") {|io| io.read}
end

#write(path, value, md5sum = nil) ⇒ Object

Write the file. It will always write the file whether it’s there or not, unless you supply an md5sum in which case it will check whether it’s different first.



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/s3aps/file_adapter.rb', line 23

def write(path, value, md5sum = nil)
just_path = path.sub /\/[^\/]*$/, ''
local_md5 = md5sum(path)
if local_md5.nil? || local_md5 != md5sum
  FileUtils.mkdir_p(File.join(@path, just_path))
    File.open(File.join(@path, path), 'w') {|outfile| 
      outfile.print(value)
    }
    true
  else
    false
  end
end