Sha256: f2e970d84c9d1272820c9e44a0081bfdfd36f9266b40f1a240fa4e79da31aa8d

Contents?: true

Size: 1.31 KB

Versions: 12

Compression:

Stored size: 1.31 KB

Contents

# frozen_string_literal: true

require 'image_optim/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

12 entries across 12 versions & 1 rubygems

Version Path
image_optim-0.31.4 lib/image_optim/handler.rb
image_optim-0.31.3 lib/image_optim/handler.rb
image_optim-0.31.2 lib/image_optim/handler.rb
image_optim-0.31.1 lib/image_optim/handler.rb
image_optim-0.31.0 lib/image_optim/handler.rb
image_optim-0.30.0 lib/image_optim/handler.rb
image_optim-0.29.0 lib/image_optim/handler.rb
image_optim-0.28.0 lib/image_optim/handler.rb
image_optim-0.27.1 lib/image_optim/handler.rb
image_optim-0.27.0 lib/image_optim/handler.rb
image_optim-0.26.5 lib/image_optim/handler.rb
image_optim-0.26.4 lib/image_optim/handler.rb