class ImageOptim::Handler

Handles processing of original to result using upto two temp files

Attributes

result[R]

Holds latest successful result

Public Class Methods

for(original) { |handler| ... } click to toggle source

with no associated block, works as new. Otherwise creates instance and passes it to block, runs cleanup and returns result of handler

# File lib/image_optim/handler.rb, line 21
def self.for(original)
  handler = new(original)
  if block_given?
    begin
      yield handler
      handler.result
    ensure
      handler.cleanup
    end
  else
    handler
  end
end
new(original) click to toggle source

original must respond to temp_path

# File lib/image_optim/handler.rb, line 10
def initialize(original)
  unless original.respond_to?(:temp_path)
    fail ArgumentError, 'original should respond to temp_path'
  end

  @original = original
  @result = nil
end

Public Instance Methods

cleanup() click to toggle source

Remove extra temp files

# File lib/image_optim/handler.rb, line 51
def cleanup
  return unless @dst
  @dst.unlink
  @dst = nil
end
process() { |src, dst| ... } click to toggle source

Yields two paths, one to latest successful result or original, second to temp path

# File lib/image_optim/handler.rb, line 37
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