Last active
April 14, 2017 18:58
-
-
Save wheeyls/8275590 to your computer and use it in GitHub Desktop.
Setting up Cache-Control for CarrierWave uploads - making sure that file names are updated to keep the cache fresh.
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
# This is for versioning files that we upload to S3. | |
# | |
# We want a unique time stamp in the name, so that we can cache files on browsers without | |
# worrying about cache-busting. | |
# | |
# The tricky part is deciding when to increment the version, this is accomplished | |
# by binding to the +before_cache+ hook. | |
# | |
# All you need to do to use this, is to call "has_versioned_filename" from an uploader, | |
# and add a string column "+mount_name+_version_token" to the model. | |
module CarrierWave::Uploader::VersionedFilename | |
def has_versioned_filename | |
before :cache, :clear_version_token! | |
include InstanceMethods | |
end | |
module InstanceMethods | |
def fog_attributes | |
{ 'Cache-Control' => 'public, max-age=315360000' } | |
end | |
def filename | |
"#{version_token!}.#{file.extension}" if original_filename.present? | |
end | |
def version_token! | |
col = "#{mounted_as}_version_token" | |
model.send(col) || model.send("#{col}=", version_token) | |
end | |
def version_token | |
Time.now.to_i | |
end | |
def clear_version_token!(file) | |
model.send "#{mounted_as}_version_token=", nil | |
end | |
end | |
end | |
CarrierWave::Uploader::Base.send :extend, CarrierWave::Uploader::VersionedFilename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment