Report abuse

module Technoweenie
  module AttachmentFu
    module InstanceMethods

      def set_from_url(source_url)
        source_uri = URI.parse(source_url)
        self.temp_data = source_uri.read

        temp_file = File.open(temp_path, 'r')
        self.content_type = File.mime_type?(temp_file)
        self.filename = clean_filename_from_uri(source_uri)
      end

      def clean_filename_from_uri(uri)
        result = basename_from_uri(uri).inspect
        if !result.include?('.')
          extension = extension_for_mimetype(content_type)
          result += ".#{extension}" if extension
        end
        result
      end

      def basename_from_uri(uri)
        if !uri.path.blank? && !File.basename(uri.path).blank?
          File.basename(uri.path)
        else
          'file'
        end
      end

      def extension_for_mimetype(mime_type)
        File.extensions.reject {|key, value| value != mime_type || key == :jpe }.keys.first
      end

    end
  end
end