Sha256: 33e7ca86e75ddece01f24cfa48c45be97fa75328037e0221a7346512715e82b5

Contents?: true

Size: 1.87 KB

Versions: 8

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

require 'digest/sha1'

module Ckeditor
  module Http
    # Create tempfile from hash
    class UploadedFile
      attr_accessor :original_filename, :content_type, :tempfile, :headers

      def initialize(hash)
        @original_filename = hash[:filename]
        @content_type      = hash[:type]
        @headers           = hash[:head]
        @tempfile          = hash[:tempfile]
        raise(ArgumentError, ':tempfile is required') unless @tempfile
      end

      def open
        @tempfile.open
      end

      def path
        @tempfile.path
      end

      def read(*args)
        @tempfile.read(*args)
      end

      def rewind
        @tempfile.rewind
      end

      def size
        @tempfile.size
      end
    end

    # Usage (paperclip example)
    # @asset.data = QqFile.new(params[:qqfile], request)
    class QqFile < ::Tempfile
      attr_reader :original_filename

      def initialize(filename, request)
        @original_filename = filename
        @request = request

        super(Digest::SHA1.hexdigest(filename))
        fetch
      end

      def fetch
        binmode
        write(body)
        rewind
        self
      end

      def content_type
        @request.content_type
      end

      def body
        if @request.raw_post.respond_to?(:force_encoding)
          @request.raw_post.force_encoding('UTF-8')
        else
          @request.raw_post
        end
      end
    end

    # Convert nested Hash to HashWithIndifferentAccess and replace
    # file upload hash with UploadedFile objects
    def self.normalize_param(*args)
      value = args.compact.first

      if value.is_a?(Hash) && value.key?(:tempfile)
        UploadedFile.new(value)
      elsif value.is_a?(String)
        QqFile.new(*args)
      elsif value.is_a?(ActionDispatch::Request)
        value.params['upload']
      else
        value
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
ckeditor-5.1.3 lib/ckeditor/http.rb
ckeditor-5.1.2 lib/ckeditor/http.rb
ckeditor-5.1.1 lib/ckeditor/http.rb
glebtv-ckeditor-4.14.1 lib/ckeditor/http.rb
ckeditor-5.1.0 lib/ckeditor/http.rb
glebtv-ckeditor-4.13.1 lib/ckeditor/http.rb
glebtv-ckeditor-4.13.0 lib/ckeditor/http.rb
ckeditor-5.0.0 lib/ckeditor/http.rb