Sha256: 1dde412d83cd92dc786f21a79f5363a8a720f60bd0151ea0b53a73a678f8d05b

Contents?: true

Size: 1.67 KB

Versions: 2

Compression:

Stored size: 1.67 KB

Contents

module Defile
  module Backend
    class FileSystem
      attr_reader :directory

      def initialize(directory, max_size: nil, hasher: Defile::RandomHasher.new)
        @hasher = hasher
        @directory = directory
        @max_size = max_size

        FileUtils.mkdir_p(@directory)
      end

      def upload(uploadable)
        Defile.verify_uploadable(uploadable, @max_size)

        id = @hasher.hash(uploadable)

        if uploadable.respond_to?(:path) and ::File.exist?(uploadable.path)
          FileUtils.cp(uploadable.path, path(id))
        else
          ::File.open(path(id), "wb") do |file|
            buffer = "" # reuse the same buffer
            until uploadable.eof?
              uploadable.read(Defile.read_chunk_size, buffer)
              file.write(buffer)
            end
            uploadable.close
          end
        end

        Defile::File.new(self, id)
      end

      def get(id)
        Defile::File.new(self, id)
      end

      def delete(id)
        FileUtils.rm(path(id)) if exists?(id)
      end

      def open(id)
        ::File.open(path(id), "rb")
      end

      def read(id)
        ::File.read(path(id)) if exists?(id)
      end

      def size(id)
        ::File.size(path(id)) if exists?(id)
      end

      def exists?(id)
        ::File.exists?(path(id))
      end

      def clear!(confirm = nil)
        raise ArgumentError, "are you sure? this will remove all files in the backend, call as `clear!(:confirm)` if you're sure you want to do this" unless confirm == :confirm
        FileUtils.rm_rf(@directory)
        FileUtils.mkdir_p(@directory)
      end

      def path(id)
        ::File.join(@directory, id)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
defile-0.2.1 lib/defile/backend/file_system.rb
defile-0.2.0 lib/defile/backend/file_system.rb