Handling File Transfers in a Heroku Environment with Net::SFTP

Handling File Transfers in a Heroku Environment with Net::SFTP

Daily readers, today’s article is a bit different. Usually, I dive into a specific Ruby or Ruby on Rails topic, but today, time is short, and I need to handle different tasks. So, I’ll share a quick but useful real-world problem I encountered.


Need Help with a Heroku Project?

Do you need to handle a project running on a Heroku server? Contact me—I can help you: https://rubystacknews.com/get-in-touch/


The Challenge

One time, I needed to download a file that was generated on the fly inside a Heroku server. Since Heroku’s filesystem is ephemeral, I had to find a way to retrieve the file manually. My approach was to copy the file to another FTP server using Net::SFTP.

The Solution


Below is the simple Ruby algorithm I used to upload the file:

require 'net/sftp'

def upload(file_path)
  begin
    Net::SFTP.start(ENV['host'], ENV['username'], password: ENV['password']) do |sftp|
      sftp.upload!(file_path, "./#{file_path}")
    end
    
    puts 'Successful'
  rescue Net::SFTP::StatusException => e
    puts "Error: #{e.message}"
  rescue Net::ReadTimeout, Net::OpenTimeout => e
    puts "Error: #{e.message}"
  end
end
        

Need Expert Ruby on Rails Developers to Elevate Your Project?

Fill out our form! >>

Need Expert Ruby on Rails Developers to Elevate Your Project?

Configuration

To make this work, you need to set up environment variables in your .env file:

host=your_host_name
username=your_ftp_username
password=your_secure_password
        

If you are using a Dockerized Ruby on Rails environment (like the one discussed in this article), you just need to update your docker-compose.yml file:

rails:
  build:
    context: ..
    dockerfile: docker_environment/Dockerfile
  container_name: env-ruby_stack_news.rails
  depends_on:
    - db
    - mailcatcher
  environment:
    host=your_host_name
    username=your_ftp_username
    password=your_secure_password
  ports:
    - 3000:3000
  tty: true
  volumes:
    - ${PWD}:/app
    - ${PWD}/.root:/root
  platform: linux/amd64        

Heroku:

Set the variables in the form to add them.

Heroku

Why This Matters

Even small tasks like this can become roadblocks if you don’t have a quick solution. Handling file transfers inside Heroku (or any cloud environment) requires a workaround due to its ephemeral nature. Net::SFTP provides a simple and efficient way to move files securely.

Hope this helps! Let me know if you have a different approach or an alternative solution.



要查看或添加评论,请登录

Germán Silva的更多文章