Sha256: 7b2c080b65d7e1d1285ae4f8bac3c08c4ca079f4e6a2842c7b9784d25d48089c

Contents?: true

Size: 1.28 KB

Versions: 14

Compression:

Stored size: 1.28 KB

Contents

require 'image_optim/image_path'

class ImageOptim
  # Handles processing of original to result using upto two temp files
  class Handler
    # Holds latest successful result
    attr_reader :result

    # original must respond to temp_path
    def initialize(original)
      unless original.respond_to?(:temp_path)
        fail ArgumentError, 'original should respond to temp_path'
      end

      @original = original
      @result = nil
    end

    # with no associated block, works as new. Otherwise creates instance and
    # passes it to block, runs cleanup and returns result of handler
    def self.for(original)
      handler = new(original)
      if block_given?
        begin
          yield handler
          handler.result
        ensure
          handler.cleanup
        end
      else
        handler
      end
    end

    # Yields two paths, one to latest successful result or original, second to
    # temp path
    def process
      @src ||= @original
      @dst ||= @original.temp_path

      return unless yield @src, @dst
      @result = @dst
      if @src == @original
        @src, @dst = @dst, nil
      else
        @src, @dst = @dst, @src
      end
    end

    # Remove extra temp files
    def cleanup
      return unless @dst
      @dst.unlink
      @dst = nil
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
image_optim-0.22.1 lib/image_optim/handler.rb
image_optim-0.22.0 lib/image_optim/handler.rb
openstreetmap-image_optim-0.21.0.1 lib/image_optim/handler.rb
image_optim-0.21.0 lib/image_optim/handler.rb
image_optim-0.20.2 lib/image_optim/handler.rb
image_optim-0.20.1 lib/image_optim/handler.rb
image_optim-0.20.0 lib/image_optim/handler.rb
image_optim-0.19.1 lib/image_optim/handler.rb
image_optim-0.19.0 lib/image_optim/handler.rb
image_optim-0.18.0 lib/image_optim/handler.rb
image_optim-0.17.1 lib/image_optim/handler.rb
image_optim-0.17.0 lib/image_optim/handler.rb
image_optim-0.16.0 lib/image_optim/handler.rb
image_optim-0.15.0 lib/image_optim/handler.rb