Skip to content

Instantly share code, notes, and snippets.

@kimihito
Created November 25, 2019 06:58
Show Gist options
  • Save kimihito/a00af1bc3b6b1ee31ec89cc173cb9deb to your computer and use it in GitHub Desktop.
Save kimihito/a00af1bc3b6b1ee31ec89cc173cb9deb to your computer and use it in GitHub Desktop.
setup for Active Storage direct upload ( Google Cloud Storage )
# lib/tasks/active_storage.rake
require 'google/cloud/storage'
namespace :active_storage do
desc 'create bucket'
task :create_bucket, [:bucket_name, :domain] => :environment do |task, args|
storage.create_bucket(args.bucket_name, location: 'us-east1') do |b|
b.cors.add_rule ["http://#{args.domain}", "https://#{args.domain}"],
'*',
headers: ['Content-Type', 'Content-Md5'],
max_age: 3600
end
end
desc 'cleanup buckets'
task :cleanup_bucket, [:bucket_name] => :environment do |task, args|
ActiveStorage::Attachment.in_batches.each_record(&:purge)
storage.bucket(args.bucket_name).delete
end
end
private
def storage
Google::Cloud::Storage.new(credentials: credentials)
end
def credentials
Google::Cloud::Storage::Credentials.new(
{
project_id: ENV.fetch('GCS_PROJECT_ID'),
private_key: ENV.fetch('GCS_PRIVATE_KEY').gsub("\\n", "\n"),
private_key_id: ENV.fetch('GCS_PRIVATE_KEY_ID'),
client_email: ENV.fetch('GCS_CLIENT_EMAIL'),
client_id: ENV.fetch('GCS_CLIENT_ID'),
client_x509_cert_url: ENV.fetch('GCS_X509_CERT_URL')
}
)
end
{
"scripts": {
"postdeploy": "bin/rails heroku_review_apps:setup",
"pr-predestroy": "bin/rails heroku_review_apps:cleanup"
},
}
# lib/tasks/heroku_review_apps.rake
# need ENV['HEROKU_APP_NAME']
namespace :heroku_review_apps do
desc 'create bucket for Heroku Reivew Apps'
task setup: :environment do
Rake::Task['active_storage:create_bucket'].invoke(ENV['HEROKU_APP_NAME'], "#{ENV['HEROKU_APP_NAME']}.herokuapp.com")
ENV['FIXTURES'] = 'users,projects,tracks' # Workaround ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "tracks" violates foreign key constraint "fk_rails_xxxxx"
Rake::Task['db:fixtures:load'].invoke
end
desc 'cleanup buckets using Heroku Review Apps'
task cleanup: :environment do
Rake::Task['active_storage:cleanup_bucket'].invoke(ENV['HEROKU_APP_NAME'], "#{ENV['HEROKU_APP_NAME']}.herokuapp.com")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment