Skip to content

Instantly share code, notes, and snippets.

@jeffrafter
Created May 28, 2015 20:30
Show Gist options
  • Save jeffrafter/2b3ffa1900c9bdf35ece to your computer and use it in GitHub Desktop.
Save jeffrafter/2b3ffa1900c9bdf35ece to your computer and use it in GitHub Desktop.
Uploading static files to S3
# Aws and static site rendering
gem 'aws-sdk', '< 2.0'
require 'static'
namespace :publish do
desc "Publish the static assets to the server"
task :static do
puts "Publishing"
static_files = [
"index.html",
"css/share.css",
"js/share.js",
"fonts/pacifico/Pacifico-webfont.eot",
"fonts/pacifico/Pacifico-webfont.svg",
"fonts/pacifico/Pacifico-webfont.ttf",
"fonts/pacifico/Pacifico-webfont.woff",
"fonts/pacifico/stylesheet.css",
"fonts/theano-didot/TheanoDidot-Regular-webfont.eot",
"fonts/theano-didot/TheanoDidot-Regular-webfont.svg",
"fonts/theano-didot/TheanoDidot-Regular-webfont.ttf",
"fonts/theano-didot/TheanoDidot-Regular-webfont.woff",
"fonts/theano-didot/stylesheet.css"
]
static = Static.new
static_files.each do |path|
puts " #{path}"
ext = File.extname(path).sub('.', '')
mime_type = Mime::Type.lookup_by_extension(ext)
static.publish(Rails.root.join('public', path), path, mime_type)
end
puts "Done"
puts ""
end
end
class Static
attr_accessor :s3, :bucket
def initialize
self.s3 = AWS::S3.new(access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'])
self.bucket = self.s3.buckets[ENV['AWS_BUCKET']]
self.bucket = self.s3.buckets.create(ENV['AWS_BUCKET']) unless bucket.exists?
end
def publish(source, path, content_type, expirable=true)
# This line incurs remote communication with AWS
obj = self.bucket.objects[path]
return if obj.exists? && !expirable
options = {
acl: :public_read,
content_type: content_type || 'text/html'
}
unless expirable
options[:cache_control] = "max-age=#{1.year.to_i}"
options[:expires] = 1.year.from_now.httpdate
end
obj.write(source, options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment