Skip to content

Instantly share code, notes, and snippets.

@jeshuaborges
Created October 23, 2012 21:04
Show Gist options
  • Save jeshuaborges/3941547 to your computer and use it in GitHub Desktop.
Save jeshuaborges/3941547 to your computer and use it in GitHub Desktop.
class S3Uploader
attr_reader :expiration, :path
def initialize
@path = "uploads/#{SecureRandom.hex}"
@expiration = 10.hours.from_now
end
def access_key_id
ENV['AWS_ACCESS_KEY_ID']
end
def secret_access_key
ENV['AWS_SECRET_ACCESS_KEY']
end
def bucket
ENV['AWS_S3_BUCKET']
end
def key
"#{path}/${filename}"
end
def acl
'public-read'
end
def max_file_size
500.megabytes
end
def fields
{
:key => key,
:acl => acl,
:policy => policy,
:signature => signature,
"AWSAccessKeyId" => access_key_id,
}
end
def url
"https://#{bucket}.s3.amazonaws.com/"
end
def policy
Base64.encode64(policy_data.to_json).gsub("\n", "")
end
def policy_data
{
expiration: expiration,
conditions: [
["starts-with", "$utf8", ""],
["starts-with", "$key", "uploads/"],
["content-length-range", 0, max_file_size],
{bucket: bucket},
{acl: acl}
]
}
end
def signature
Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
secret_access_key, policy
)
).gsub("\n", "")
end
end
require 's3uploader'
module UploadHelper
def photo_form_tag(options={}, &block)
# Introduce standard form options.
options = {
method: "post",
authenticity_token: false,
multipart: true
}.deep_merge(options)
form = ImageUploader.file? ? :rails_uploader_form : :s3_uploader_form
send(form, options, &block)
end
def rails_uploader_form(options={}, &block)
form_tag(upload_photos_path, {multipart: true}.merge(options), &block)
end
def s3_uploader_form(options={}, &block)
uploader = S3Uploader.new
# The path the the file is uploaded to, not used by rails uploader.
options.deep_merge!({
data: {
:'upload-path' => uploader.path
}
})
form_tag(uploader.url, options) do
uploader.fields.map do |name, value|
hidden_field_tag(name, value)
end.join.html_safe + capture(&block)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment