Sha256: 37c44fcb21c3edd3bb72dcc359181bf25e78cb5a8b2db525ab7a7a97b495a634

Contents?: true

Size: 1.72 KB

Versions: 2

Compression:

Stored size: 1.72 KB

Contents

# coding: utf-8
require 'securerandom'

module GyomuRuby
  module AmazonWebService
    class FileBucket
      attr_accessor :backend

      extend Forwardable
      def_delegators :backend, *%w[bucket get delete]

      def initialize(bucket = 'bucket')
        @backend = Rails.env.production? || Rails.env.staging? ?  RichMan.new(bucket) : PoorMan.new(bucket)
      end

      def put(io)
        "#{Time.now.strftime('%Y%m%d%H%M')}_#{SecureRandom.hex(5)}".tap do |key|
          @backend.put(key, io)
        end
      end

      class PoorMan
        require 'fileutils'

        attr_reader :bucket

        def initialize(bucket)
          @bucket = bucket
          path = Rails.root.join('tmp', @bucket)
          FileUtils.mkdir_p path unless FileTest.exist? path
        end

        def put(key, io)
          File.open(Rails.root.join('tmp', @bucket, key), 'w:BINARY') {|f| f.write(io.read)}
        end

        def get(key)
          File.open(Rails.root.join('tmp', @bucket, key), 'r:BINARY') {|f| f.read }
        end

        def delete(key)
          !!FileUtils.rm_r(Rails.root.join('tmp', @bucket, key))
        end
      end

      class RichMan
        require 'aws/s3'

        attr_reader :bucket

        def initialize(bucket)
          @bucket = bucket
          ::AWS::S3::Bucket.find(@bucket)
        rescue ::AWS::S3::NoSuchBucket
          ::AWS::S3::Bucket.create(@bucket)
        end

        def put(key, io)
          ::AWS::S3::S3Object.store(key, io, @bucket)
        end

        def get(key)
          ::AWS::S3::S3Object.value(key, @bucket) rescue nil
        end

        def delete(key)
          ::AWS::S3::S3Object.delete(key, @bucket) rescue false
        end
      end
    end
  end

  AWS = AmazonWebService
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
gyomu_ruby-0.0.5 lib/gyomu_ruby/amazon_web_service/file_bucket.rb
gyomu_ruby-0.0.4 lib/gyomu_ruby/amazon_web_service/file_bucket.rb