Created
June 21, 2013 14:16
-
-
Save codenamev/5831463 to your computer and use it in GitHub Desktop.
Custom file names with Carrierwave and Amazon S3
This file contains hidden or 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
# model | |
class Attachment < ActiveRecord::Base | |
mount_uploader :document, DocumentUploader | |
# these methods fix the filename persistance issue | |
def read_uploader(column) | |
self[column] | |
end | |
def write_uploader(column, identifier) | |
self[column] = identifier | |
end | |
end |
This file contains hidden or 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
# Carrierwave initializer in `config/initializers/carrierwave.rb` | |
CarrierWave.configure do |config| | |
config.fog_credentials = { | |
:provider => 'AWS', | |
:aws_access_key_id => 'replace-this-with-your-access-key-id', | |
:aws_secret_access_key => 'replace-this-with-your-secret-access-key' | |
} | |
config.fog_directory = 'rename-this-to-a-custom-directory-for-your-app' | |
config.fog_public = false | |
config.fog_attributes = {'Cache-Control'=>'max-age=300000000'} | |
config.cache_dir = "#{Rails.root}/tmp/uploads" | |
end |
This file contains hidden or 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
# uploader | |
class DocumentUploader < CarrierWave::Uploader::Base | |
storage :fog | |
def store_dir | |
"uploads/#{Rails.env}/#{model.class.to_s.underscore.pluralize}/#{mounted_as}/#{model.id}" | |
end | |
end | |
def store_path(for_file = filename) | |
"uploads/#{Rails.env}/#{model.class.to_s.underscore.pluralize}/#{mounted_as}/#{model.id}/#{for_file}" | |
end | |
def filename(uploaded_file = file) | |
if uploaded_file.present? | |
"Document with custom title ##{model.id}.#{uploaded_file.extension}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment