Sha256: 304015da5bb4ed1c96de305f3c4ccb5525bf16322c6715667cf2a1a7ab4b563d

Contents?: true

Size: 1.1 KB

Versions: 14

Compression:

Stored size: 1.1 KB

Contents

# encoding: utf-8
require 'cocaine'

module Ckeditor
  module Utils
    class ContentTypeDetector
      EMPTY_CONTENT_TYPE = 'inode/x-empty'
      DEFAULT_CONTENT_TYPE = 'application/octet-stream'

      def initialize(file_path)
        @file_path = file_path
      end

      # content type detection strategy:
      #
      # 1. empty file: returns 'inode/x-empty'
      # 2. nonempty file: if the file is not empty then returns the content type using file command
      # 3. invalid file: file command raises error and returns 'application/octet-stream'

      def detect
        empty_file? ? EMPTY_CONTENT_TYPE : content_type_from_file_command
      end

      private

      def empty_file?
        return true if @file_path.blank?
        File.exists?(@file_path) && File.size(@file_path) == 0
      end

      def content_type_from_file_command
        type = begin
          Cocaine::CommandLine.new('file', '-b --mime-type :file').run(file: @file_path)
        rescue Cocaine::CommandLineError => e
          # TODO: log command failure
          DEFAULT_CONTENT_TYPE
        end.strip
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 4 rubygems

Version Path
danabr75-ckeditor-4.1.6 lib/ckeditor/utils/content_type_detector.rb
glebtv-ckeditor-4.6.0 lib/ckeditor/utils/content_type_detector.rb
glebtv-ckeditor-4.5.10.3 lib/ckeditor/utils/content_type_detector.rb
glebtv-ckeditor-4.5.10.2 lib/ckeditor/utils/content_type_detector.rb
glebtv-ckeditor-4.5.10.1 lib/ckeditor/utils/content_type_detector.rb
glebtv-ckeditor-4.5.7.1 lib/ckeditor/utils/content_type_detector.rb
glebtv-ckeditor-4.5.7 lib/ckeditor/utils/content_type_detector.rb
ckeditor_custom_controller-4.1.6 lib/ckeditor/utils/content_type_detector.rb
ckeditor-4.1.6 lib/ckeditor/utils/content_type_detector.rb
ckeditor-4.1.5 lib/ckeditor/utils/content_type_detector.rb
ckeditor-4.1.4 lib/ckeditor/utils/content_type_detector.rb
ckeditor-4.1.3 lib/ckeditor/utils/content_type_detector.rb
ckeditor-4.1.2 lib/ckeditor/utils/content_type_detector.rb
ckeditor-4.1.1 lib/ckeditor/utils/content_type_detector.rb