Sha256: 08c6238369b14ac0044990b0de0d66852114c10ca2da91e8efcda36bd2924045

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

require 'paperclip'
require 'tus-server'

module Paperclip
  module Tus
    class Adapter < Paperclip::AbstractAdapter
      REGEXP = /\A[\da-f]{32}\Z/

      def initialize(target, _options = {})
        ensure_tus_filesystem_storage!

        @uid = target
        @file_path = tus_file_path.to_s
        @info = tus_info
        cache_current_values
        # passing options to super for paperclip 5.2.x
        super if Paperclip::VERSION.to_f > 5.1
      end

      private

      def cache_current_values
        self.original_filename = @info.metadata['filename']
        @tempfile = copy_to_tempfile(@file_path)
        @content_type = Paperclip::ContentTypeDetector.new(@file_path).detect
        @size = @info.length
      end

      def tus_info
        ::Tus::Info.new(tus_storage.read_info(@uid))
      end

      def tus_file_path
        # FIXME: private method
        tus_storage.send(:file_path, @uid)
      end

      def tus_storage
        ::Tus::Server.opts[:storage]
      end

      def ensure_tus_filesystem_storage!
        return if tus_storage.class == ::Tus::Storage::Filesystem

        raise 'Paperclip tus adapter does not support ' \
          "#{tus_storage.class.name}! Please set Tus::Server.opts[:storage] " \
          'to Tus::Storage::Filesystem.new(cache_directory)'
      end

      def copy_to_tempfile(src_path)
        FileUtils.cp(src_path, destination.path)
        destination
      end
    end
  end
end

Paperclip.io_adapters.register Paperclip::Tus::Adapter do |target|
  target.is_a?(String) && target =~ Paperclip::Tus::Adapter::REGEXP
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
paperclip-tus-0.3.1 lib/paperclip/tus/adapter.rb
paperclip-tus-0.3.0 lib/paperclip/tus/adapter.rb