Sha256: da0777e55b2af7573e630c4d7f81ea263c0c19cec3dc60be13f1da99c1963d69

Contents?: true

Size: 880 Bytes

Versions: 3

Compression:

Stored size: 880 Bytes

Contents

require "terrapin"
require "mime-types"

module Anyfetch
  module OriginalFilename
    module ContentType
      def original_filename
        if meta.include? 'content-disposition'
          match = meta['content-disposition'].match(/filename=(\"?)(.+)\1/)
          return match[2] unless match.nil?
        end

        filename = ::File.basename(base_uri.path)
        ext = ::File.extname(filename)

        cmd = Terrapin::CommandLine.new('/usr/bin/file', '--mime-type -b :file')
        begin
          mime_type = cmd.run(:file => path)
        rescue
          mime_type = meta['content-type']
        end

        if mime = MIME::Types[mime_type.to_s.strip].first
          mime_ext = mime.extensions.first
          ext != mime_ext ? [::File.basename(filename, ext), '.', mime_ext].join : filename
        else
          filename
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
anyfetch-0.1.7 lib/anyfetch/original_filename/content_type.rb
anyfetch-0.1.6 lib/anyfetch/original_filename/content_type.rb
anyfetch-0.1.5 lib/anyfetch/original_filename/content_type.rb