Sha256: 812b6a53ca07bc7f28f80b04e5e64996ca57f9b39f2775d4c6f53fc03664897a

Contents?: true

Size: 1.52 KB

Versions: 2

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true

module Paperweight
  # Handles putting and deleting files from different kinds of storage.
  module Storage
    # A storage adapter for Amazon AWS S3.
    class Remote
      attr_reader :client

      def initialize
        @client = ::Aws::S3::Client.new(Paperweight.config.credentials)
      end

      def delete(key)
        client.delete_object(bucket: Paperweight.config.bucket, key: key)
      end

      def put(file, key)
        client.put_object(
          acl: 'public-read',
          bucket: Paperweight.config.bucket,
          key: key,
          content_type: Paperclip::ContentTypeDetector.new(file.path).detect,
          content_disposition: 'attachment',
          body: file
        )
      end
    end

    # A storage adapter for a local filesystem.
    class Local
      attr_reader :root

      def initialize(root)
        @root = root
      end

      def delete(key)
        FileUtils.rm(File.join(root, key))
      end

      def put(file, key)
        filepath = File.join(root, key)
        FileUtils.mkdir_p(File.dirname(filepath))
        FileUtils.cp(file.path, filepath)
      end
    end

    class << self
      def adapter
        @adapter ||=
          case Rails.env
          when 'production'  then Remote.new
          when 'development' then local_for('public')
          when 'test'        then local_for('tmp')
          end
      end

      private

      def local_for(directory)
        Local.new(Rails.root.join(directory, 'paperweight').to_s.freeze)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
paperweight-0.0.5 lib/paperweight/storage.rb
paperweight-0.0.4 lib/paperweight/storage.rb