Sha256: c09a49948d85882e040f2917b78b64023884803aca7626ccf1844a3e29ed5115

Contents?: true

Size: 1.77 KB

Versions: 14

Compression:

Stored size: 1.77 KB

Contents

require "active_support/core_ext/module/delegation"

module Paperclip
  class AbstractAdapter
    OS_RESTRICTED_CHARACTERS = %r{[/:]}.freeze

    attr_reader :content_type, :original_filename, :size, :tempfile
    delegate :binmode, :binmode?, :close, :close!, :closed?, :eof?, :path, :readbyte, :rewind, :unlink, to: :@tempfile
    alias :length :size

    def initialize(target, options = {})
      @target = target
      @options = options
    end

    def fingerprint
      @fingerprint ||= begin
        digest = @options.fetch(:hash_digest).new
        File.open(path, "rb") do |f|
          buf = ""
          digest.update(buf) while f.read(16384, buf)
        end
        digest.hexdigest
      end
    end

    def read(length = nil, buffer = nil)
      @tempfile.read(length, buffer)
    end

    def inspect
      "#{self.class}: #{original_filename}"
    end

    def original_filename=(new_filename)
      return unless new_filename

      @original_filename = new_filename.gsub(OS_RESTRICTED_CHARACTERS, "_")
    end

    def nil?
      false
    end

    def assignment?
      true
    end

    private

    def destination
      @destination ||= TempfileFactory.new.generate(@original_filename.to_s)
    end

    def copy_to_tempfile(src)
      link_or_copy_file(src.path, destination.path)
      destination
    end

    def link_or_copy_file(src, dest)
      begin
        Paperclip.log("Trying to link #{src} to #{dest}")
        FileUtils.ln(src, dest, force: true) # overwrite existing
      rescue Errno::EXDEV, Errno::EPERM, Errno::ENOENT, Errno::EEXIST => e
        Paperclip.log(
          "Link failed with #{e.message}; copying link #{src} to #{dest}"
        )
        FileUtils.cp(src, dest)
      end

      @destination.close
      @destination.open.binmode
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
kt-paperclip-7.2.2 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-7.2.1 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-7.2.0 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-6.4.2 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-7.1.1 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-7.1.0 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-7.0.1 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-7.0.0 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-6.4.1 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-6.4.0 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-6.3.0 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-6.2.2 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-6.2.1 lib/paperclip/io_adapters/abstract_adapter.rb
kt-paperclip-6.2.0 lib/paperclip/io_adapters/abstract_adapter.rb