(1) Install AWS SDK.

gem 'aws-sdk', '~> 2'

(2) Create an IAM user with S3 full privilege. Get the Access Key ID and Access Key, as well as the region you want to operate in.

s3_region = 'us-east-1'
s3_access_key_id = 'XXXXXX'
s3_access_key = 'YYYYYY'
s3_bucket_name = 'my-test-bucket-123'

(3) Create an AWS client.

client = Aws::S3::Client.new(
    region: s3_region,
    credentials: Aws::Credentials.new(s3_access_key_id, s3_access_key)

(4) Create an S3 object from the client.

object = Aws::S3::Object.new(
	client: client,
	bucket_name: s3_bucket_name,
	key: 'filename'

(5) Upload a file on disk.

	acl: 'public-read', 
	content_type: 'text/plain',
	cache_control: 'public, max-age=604800'

(6) Or upload a text string render dynamically.

    body: content,
    acl: 'public-read',
    content_type: 'text/plain',
    cache_control: 'public, max-age=604800'
  • Check the type of ACL here for the most suitable config.
  • Cache-Control is important, especially when working with public accessible files and CDN such as CloudFront.

(7) Get the public URL of the uploaded file.

url = object.public_url # Public URL

(8) If your S3 has CloudFront configured. The URL will be:

url = "#{cloud_front_url}/#{key}"