Skip to content

Instantly share code, notes, and snippets.

@sandro
Created July 22, 2010 22:19
Show Gist options
  • Save sandro/486703 to your computer and use it in GitHub Desktop.
Save sandro/486703 to your computer and use it in GitHub Desktop.
Carrierwave file cache on heroku
class CachedImagesController < ApplicationController
def show
path = File.join(ImageUploader.cache_dir, params[:path], params[:name])
extension = File.extname(params[:name])[1..-1]
headers['Cache-Control'] = 'public; max-age=300'
send_data File.read(path), :disposition => 'inline', :type => Mime::Type.lookup_by_extension(extension)
end
end
Rails.configuration.after_initialize do
CarrierWave.configure do |config|
config.cache_dir = File.join(Rails.root, 'tmp/uploads')
end
end
class ImageUploader < CarrierWave::Uploader::Base
# ...
def url
if cached?
File.join('/cached_images', cache_name)
else
super
end
end
# ...
end
Mime::Type.register "image/jpeg", :jpg, [], %w(jpg jpeg)
Mime::Type.register "image/png", :png
# needs more secure constraints
match 'cached_images/:path/:name' => 'cached_images#show', :constraints => {:name => /[\w\-.]+/}
@gduquesnay
Copy link

What did you end up using for the "more secure constraints" ?

@sandro
Copy link
Author

sandro commented Dec 25, 2010

We switched hosting proividers before pushing to production. The concern is that you're doing a File.read on an operating system path provided by an outside source (the requestor).
Maybe the user requests /etc/passwd or something. I saw another code snippet constrain the route with a regexp but I'm no security expert so I can't provide one for you. Use your discretion, it may not be a problem for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment