Episodes

Resources

Download Source Code

Summary

# Terminal
rails credentials:edit --environment development
rails active_storage:install
rails db:migrate

# config/storage.yml
amazon:
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  region: us-east-1
  bucket: driftingruby-episode

# config/environments/development.rb
config.active_storage.service = :amazon

# Gemfile
gem 'image_processing', '~> 1.2'
gem 'aws-sdk-s3', require: false

# models/user.rb
class User < ApplicationRecord
  has_one_attached :avatar
end

# users_controller
params.require(:user).permit(:first_name, :last_name, :avatar)

# views/users/_form.html.erb
  <div class="field">
    <%= form.label :avatar %>
    <%= form.file_field :avatar %>
  </div>

# views/users/index.html.erb
<%= image_tag cdn_url(user.avatar.variant(resize_to_limit: [30, 30])) if user.avatar.attached? %>

# views/users/show.html.erb
  <%= image_tag cdn_url(@user.avatar.variant(resize_to_limit: [30, 30])) if @user.avatar.attached? %><br>
  <%= image_tag cdn_url(@user.avatar.variant(resize_to_limit: [100, 100])) if @user.avatar.attached? %><br>
  <%= image_tag cdn_url(@user.avatar) if @user.avatar.attached? %>

# config/routes.rb
  direct :cdn do |blob|
    if Rails.env.development? || Rails.env.test?
      route = blob.is_a?(ActiveStorage::Variant) ? :rails_representation : :rails_blob
      route_for(route, blob)
    else
      # File.join(Rails.application.credentials.cloudfront_url, blob.key)
      File.join('https://dvakr6u567wbi.cloudfront.net', blob.key)
    end
  end
  # cdn_url(user.avatar)