public
Last active

Utilize S3 as a storage mechanism for Rails assets

  • Download Gist
tddium.rake
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
namespace :tddium do
class AssetS3
 
BUCKET = "tddium_assets"
KEEP_AROUND = 7.days
 
def initialize(branch)
@branch = branch
end
 
def pre
download_branch_assets
end
 
def post
upload_branch_assets
clean_old_branches
end
 
protected
 
def download_branch_assets
object = s3_object
object = s3_object('master') unless object.exists?
return unless object.exists?
 
ensure_directories_exists
 
File.open(gzip_path, 'wb') do |io|
object.read do |chunk|
io.write(chunk)
end
end
 
`cd #{asset_path} && tar -zxvf #{gzip_path} -C ./`
end
 
def upload_branch_assets
ensure_directories_exists
 
`cd #{asset_path} && tar -zcvf #{gzip_path} ./`
object = s3_object
file = File.open(gzip_path, 'r')
object.write(file, :content_encoding => 'utf-8')
end
 
 
def clean_old_branches
bucket.objects.each do |object|
last_mod = object.last_modified rescue nil
if last_mod && last_mod < KEEP_AROUND.ago
object.delete
end
end
end
 
 
 
 
def s3
@s3 ||= begin
s3_config = YAML.load_file("#{Rails.root}/config/s3.yml")['test']
AWS::S3.new(
:access_key_id => s3_config['access_key_id'],
:secret_access_key => s3_config['secret_access_key']
)
end
end
 
def bucket
@bucket ||= begin
s3.buckets.create(BUCKET)
s3.buckets[BUCKET]
end
end
 
def s3_object(branch_name = @branch)
bucket.objects["#{branch_name}.tar.gz"]
end
 
 
def ensure_directories_exists
`mkdir -p #{asset_path}`
`mkdir -p tmp`
end
 
 
def gzip_path
Rails.root.join('tmp', 'assets.tar.gz')
end
 
def asset_path
prefix = Rails.application.config.assets.prefix.gsub(/^\//, '')
Rails.root.join('public', prefix)
end
 
 
end
 
desc "Download S3 Assets"
task :download_assets => :environment do
AssetS3.new(get_current_branch).pre
end
 
desc "Upload S3 Assets"
task :upload_assets => :environment do
AssetS3.new(get_current_branch).post
end
desc "pre_hook"
task :pre_hook do
Rake::Task['tddium:download_assets'].invoke
 
puts 'precompiling assets'
Rake::Task['assets:precompile'].invoke
end
 
desc "post_build_hook"
task :post_build_hook do
tag_green_build
Rake::Task['tddium:upload_assets'].invoke
end
 
def get_current_branch
`git symbolic-ref HEAD 2>/dev/null | cut -d"/" -f 3-`.strip
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.