Class: Shrine::Storage::Ftp

Inherits:
Object
  • Object
show all
Defined in:
lib/shrine/storage/ftp.rb

Overview

The Ftp storage handles uploads to Ftp via FTP using the `shrine-ftp` gem:

gem "shrine-ftp"

It is initialized with the following 4 required arguments:

storage = Shrine::Storage::Ftp.new(
  host: "ftp.hosturl.com",
  user: "username",
  passwd: "yourpassword",
  dir: "path/to/upload/files/to"
)

It can also take an optional argument `prefix` as the URL or domain to prefix to your file location. This comes in handy when your ftp host and your file prefix url are different, such as if you're using a CDN.

Instance Method Summary collapse

Constructor Details

#initialize(host:, user:, password:, dir:, prefix: nil) ⇒ Ftp

Initializes a storage for uploading to Ftp

Parameters:

host

ftp host

user

ftp username

password

ftp password

dir

directory (will be created if it doesn't exist) to upload files to

prefix

(optional) url hostname if files actually live in a different URL (or are served by CDN). If none is provided, defaults to `host`

Returns:

An object that represents the Ftp storage.



43
44
45
46
47
48
49
# File 'lib/shrine/storage/ftp.rb', line 43

def initialize(host:, user:, password:, dir:, prefix: nil)
  @host = host
  @user = user
  @passwd = password
  @dir = dir
  @prefix = prefix || host
end

Instance Method Details

#delete(id) ⇒ Object

Deletes the file via FTP.



79
80
81
82
83
84
85
86
87
# File 'lib/shrine/storage/ftp.rb', line 79

def delete(id)
  if exists?(id)
    ftp = Net::FTP.open(@host, @user, @passwd)
    change_or_create_directory(ftp)
    ftp.delete(id)
    return true
  end
  return false
end

#exists?(id) ⇒ Boolean

Returns a boolean based on whether the file exists/



71
72
73
74
75
76
# File 'lib/shrine/storage/ftp.rb', line 71

def exists?(id)
  uri = URI(url(id))
  request = Net::HTTP.new uri.host
  response = request.request_head uri.path
  return response.code.to_i != 404
end

#open(id) ⇒ Object

Downloads the file



66
67
68
# File 'lib/shrine/storage/ftp.rb', line 66

def open(id)
  Down.download(url(id))
end

#to_sObject



89
90
91
# File 'lib/shrine/storage/ftp.rb', line 89

def to_s
  "#<Shrine::Storage::Ftp @host='#{@host}'>"
end

#upload(io, id, shrine_metadata: {}, **upload_options) ⇒ Object

Starts an FTP connection, changes to the appropriate directory (or creates it), and uses .putbinaryfile() to upload the file.



53
54
55
56
57
58
# File 'lib/shrine/storage/ftp.rb', line 53

def upload(io, id, shrine_metadata: {}, **upload_options)
  path_and_file = build_path_and_file(io)
  ftp = Net::FTP.open(@host, @user, @passwd)
  change_or_create_directory(ftp)
  ftp.putbinaryfile(path_and_file, id)
end

#url(id, **options) ⇒ Object

Returns the URL of where the file is assumed to be, based on `prefix`



61
62
63
# File 'lib/shrine/storage/ftp.rb', line 61

def url(id, **options)
  return [@prefix, @dir, id].join('/')
end