Class: FileClient

Inherits:
Object
  • Object
show all
Defined in:
app/clients/file_client.rb

Overview

Class to manage saving and deleting files from the filesystem. Files are uploaded and deleted from the “uploads” folder under the Rails root.

Class Method Summary collapse

Class Method Details

.delete(user_id, folder, filename) ⇒ Object

Delete a file from the filesystem. Accepts as arguments:

  • the id of the user who is deleting the file

  • the folder under which should be the file (relative to Rails root)

  • the filename to delete


31
32
33
34
35
36
37
38
39
40
# File 'app/clients/file_client.rb', line 31

def self.delete(user_id, folder, filename)
  filepath = user_file_path user_id, folder, filename
  if FileTest.exists? filepath
    Rails.logger.info "deleting file #{filepath}"
    File.delete filepath
  else
    Rails.logger.error "trying to delete non-existing file #{filepath}"
  end
  return nil
end

.exists?(user_id, folder, filename) ⇒ Boolean

Returns a boolean: true if a file with the passed filename exists, false otherwise. Accepts as arguments:

  • the id of the user who owns the file, if it exists

  • the folder in which to search

  • the filename

Returns:

  • (Boolean)

70
71
72
73
74
75
76
77
78
79
80
# File 'app/clients/file_client.rb', line 70

def self.exists?(user_id, folder, filename)
  filepath = user_file_path user_id, folder, filename
  Rails.logger.info "searching for file #{filepath}"
  exists = FileTest.exists? filepath
  if exists
    Rails.logger.info "#{filepath} exists"
  else
    Rails.logger.info "#{filepath} does not exist"
  end
  return exists
end

.read(user_id, folder, filename) ⇒ Object

Read a file from the filesystem. Accepts as arguments:

  • the id of the user who is reading the file

  • the folder under which the file should be (relative to Rails root)

  • the filename to be read

Returns the file contents if it exists, nil otherwise.


51
52
53
54
55
56
57
58
59
60
61
# File 'app/clients/file_client.rb', line 51

def self.read(user_id, folder, filename)
  filepath = user_file_path user_id, folder, filename
  if FileTest.exists? filepath
    Rails.logger.info "reading file #{filepath}"
    contents = File.read filepath
  else
    Rails.logger.error "trying to read non-existing file #{filepath}"
  end

  return contents
end

.save(user_id, folder, filename, content) ⇒ Object

Save a file in the filesystem. Accepts as arguments:

  • the id of the user who is saving the file

  • the folder under which the file will be saved (relative to Rails root)

  • the filename

  • the contents of the file.


15
16
17
18
19
20
21
22
# File 'app/clients/file_client.rb', line 15

def self.save(user_id, folder, filename, content)
  filepath = user_file_path user_id, folder, filename
  # Create folder if necessary
  FileUtils.mkdir_p File.dirname(filepath)
  Rails.logger.info "Saving file #{filepath}"
  File.open(filepath, 'w'){|file| file.write content}
  return nil
end