public
Last active

Rake task for uploading Rails 3.1 compiled assets to Amazon S3 storage

  • Download Gist
as3.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
# 1) Put 's3' gem in Gemfile.
# 2) Create as3.yml configuration for S3
# 3) Create initializer for as3.yml
# 4) Make "assets" folder inside your bucket
# 5) After running task run "RAILS_ENV=production rake assets:precompile"
# 6) Invoke task by running "rake as3:upload"
 
namespace :as3 do
desc "Uploads compiled assets (public/assets) to Amazone AS3"
task :upload do
AS3_CONFIG = YAML.load_file("#{Rails.root.to_s}/config/as3.yml")[Rails.env]
service = S3::Service.new(:access_key_id =>AS3_CONFIG["access_key_id"],
:secret_access_key =>AS3_CONFIG["secret_access_key"])
bucket = service.buckets.find(AS3_CONFIG["bucket"])
# Upload assets
assets = bucket.objects.find("assets/")
path = "#{Rails.root.to_s}/public"
files = Dir["#{path}/assets/**/**"].map { |f| f[path.length+1,f.length-path.length] }
files.each do |f|
if File.file? "#{path}/#{f}" # Only files.
# MIME type (S3 sux at MIME detection)
mimetype = `file -ib #{path}/#{f}`.gsub(/\n/,"") # if "-ib" does not work on your OS use "-Ib"
mimetype = mimetype[0,mimetype.index(';')]
mimetype = "application/javascript" if "#{path}/#{f}" =~ /\.js/
mimetype = "text/css" if "#{path}/#{f}" =~ /\.css/
 
# Don't upload existing
begin
existing = bucket.objects.find(f)
# puts "File: #{f} - Not updated!"
rescue => e
new_object = bucket.objects.build(f)
new_object.content = open("#{path}/#{f}")
new_object.content_type = mimetype
new_object.save
puts "File: #{f} - Upload complete."
end
end
end
puts "Done."
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.