Skip to content

Instantly share code, notes, and snippets.

@mnelson
Created November 24, 2012 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnelson/4141068 to your computer and use it in GitHub Desktop.
Save mnelson/4141068 to your computer and use it in GitHub Desktop.
Utilize S3 as a storage mechanism for Rails assets
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment