Created
May 28, 2015 20:30
Uploading static files to S3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Aws and static site rendering | |
gem 'aws-sdk', '< 2.0' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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