Skip to content

Instantly share code, notes, and snippets.

@avsej
Created March 26, 2010 17:49
Show Gist options
  • Save avsej/345166 to your computer and use it in GitHub Desktop.
Save avsej/345166 to your computer and use it in GitHub Desktop.
This rack middleware can be used to detect content type of attachment
require 'shellwords'
class FixAttachmentContentType
def initialize(app)
@app = app
end
def call(env)
if form_hash = env["rack.request.form_hash"]
fix_tempfiles(form_hash)
end
@app.call(env)
end
# this method performs recursive traversal of hash, finds sub-hashes
# with :tempfile key and fix content type via file utility
#
def fix_tempfiles(form_hash)
form_hash.each do |key, val|
if val.is_a?(Hash)
fix_tempfiles(val)
if val[:tempfile]
val[:type] = `file -b -i #{val[:tempfile].path.shellescape}`.chomp.gsub(/;.*$/, '')
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment