Sha256: 3e44565d07a74fc13c41b67702d836cdcb5fcd6b812bf1ea8fb119614f4a7ec4

Contents?: true

Size: 1.5 KB

Versions: 6

Compression:

Stored size: 1.5 KB

Contents

# encoding: UTF-8

module Spontaneous::Storage
  class Local < Backend
    attr_reader :root

    def initialize(root_directory, url_path, accepts = nil)
      @root, @url_path, @accepts = ::File.expand_path(root_directory), url_path, accepts
    end

    def copy(existing_file, media_path, mimetype)
      dest_path = create_absolute_path(media_path)
      copy_file(existing_file, dest_path)
      set_permissions(dest_path)
      dest_path
    end

    def copy_file(existing_file, dest_path)
      if existing_file.respond_to?(:read)
        File.open(dest_path, "wb") do |f|
          f.binmode
          while chunk = existing_file.read(8192)
            f.write(chunk)
          end
        end
      else
        FileUtils.copy_file(existing_file, dest_path)
      end
    end

    def open(relative_path, mimetype, mode, &block)
      dest_path = create_absolute_path(relative_path)
      File.open(dest_path, mode) do |f|
        f.binmode
        block.call(f)
      end
      set_permissions(dest_path)
    end

    def create_absolute_path(relative_path)
      absolute_path = File.join(root, join_path(relative_path))
      absolute_dir = File.dirname(absolute_path)
      FileUtils.mkdir_p(absolute_dir) unless File.exist?(absolute_dir)
      absolute_path
    end

    def join_path(path)
      File.join(*path)
    end

    def public_url(path)
      File.join(@url_path, join_path(path))
    end

    def local?
      true
    end

    def set_permissions(filepath)
      File.chmod(0644, filepath)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spontaneous-0.2.0.beta1 lib/spontaneous/storage/local.rb
spontaneous-0.2.0.alpha7 lib/spontaneous/storage/local.rb
spontaneous-0.2.0.alpha6 lib/spontaneous/storage/local.rb
spontaneous-0.2.0.alpha5 lib/spontaneous/storage/local.rb
spontaneous-0.2.0.alpha4 lib/spontaneous/storage/local.rb
spontaneous-0.2.0.alpha3 lib/spontaneous/storage/local.rb