Skip to content

Instantly share code, notes, and snippets.

@kossnocorp
Created February 20, 2010 09:08
Show Gist options
  • Select an option

  • Save kossnocorp/309602 to your computer and use it in GitHub Desktop.

Select an option

Save kossnocorp/309602 to your computer and use it in GitHub Desktop.
module Paperclip
module Storage
module Sftp
def self.extended base
require 'net/ssh'
require 'net/sftp'
base.instance_eval do
@host = @options[:sftp_host]
@user = @options[:sftp_user]
@password = @options[:sftp_password]
end
end
def ssh
@ssh_connection ||= Net::SSH.start @host, @user, :password => @password
end
def exists? style = default_style
ssh.exec!("ls #{path(style)} 2>/dev/null") ? true : false
end
def to_file style = default_style
@queued_for_write[style] || (ssh.sftp.file.open(path(style), 'rb') if exists?(style))
end
alias_method :to_io, :to_file
def flush_writes #:nodoc:
RAILS_DEFAULT_LOGGER.debug("[paperclip] Writing files for #{name}")
@queued_for_write.each do |style, file|
file.close
ssh.exec! "mkdir -p #{File.dirname(path(style))}"
RAILS_DEFAULT_LOGGER.debug("[paperclip] -> #{path(style)}")
ssh.sftp.upload!(file.path, path(style))
ssh.sftp.setstat!(path(style), :permissions => 0644)
end
@queued_for_write = {}
end
def flush_deletes #:nodoc:
RAILS_DEFAULT_LOGGER.debug("[paperclip] Deleting files for #{name}")
@queued_for_delete.each do |path|
begin
RAILS_DEFAULT_LOGGER.debug("[paperclip] -> #{path}")
ssh.sftp.remove(path)
FileUtils.rm(path) if File.exist?(path)
rescue Net::SFTP::StatusException
# ignore file-not-found, let everything else pass
end
begin
while(true)
path = File.dirname(path)
sftp.rmdir(path)
end
rescue Net::SFTP::StatusException
# Stop trying to remove parent directories
end
end
@queued_for_delete = []
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment