Skip to content

Instantly share code, notes, and snippets.

@matthutchinson
Created January 13, 2012 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthutchinson/1607142 to your computer and use it in GitHub Desktop.
Save matthutchinson/1607142 to your computer and use it in GitHub Desktop.
Broken or missing image interceptor
# lib/rack_image_interceptor.rb
module Rack
class ImageInterceptor
def initialize(app)
@app = app
end
def respond_with_placeholder_image(path)
file = ::File.open(path)
[200, {'Content-Type' => file.content_type}, [file.read]]
end
def call(env)
case env['PATH_INFO']
when /^\/system\/images\/[0-9]+\/(.+)$/
placeholder_path = './public/images/placeholders'
image_size = $1
path_with_size = "#{placeholder_path}/property_placeholder_#{image_size}.gif"
if ::File.exists?(path_with_size)
respond_with_placeholder_image path_with_size
elsif ::File.exists?("#{placeholder_path}/property_placeholder.gif")
respond_with_placeholder_image("#{placeholder_path}/property_placeholder.gif")
end
when /^\/system\/avatars\/[0-9]+\/(.+)$/
respond_with_placeholder_image('./public/images/user_thumb.png')
else
response = @app.call(env)
end
end
end
end
# Then add this to your Rails environment file (e.g. development.rb)
# require 'lib/rack_image_interceptor.rb'
# config.middleware.use ::Rack::ImageInterceptor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment