Class: ImageOptim::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/image_optim/handler.rb

Overview

Handles processing of original to result using upto two temp files

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(original) ⇒ Handler

original must respond to temp_path


10
11
12
13
14
15
16
17
# 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

Instance Attribute Details

#resultObject (readonly)

Holds latest successful result


7
8
9
# File 'lib/image_optim/handler.rb', line 7

def result
  @result
end

Class Method Details

.for(original) ⇒ Object

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


21
22
23
24
25
26
27
28
29
30
31
32
33
# 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

Instance Method Details

#cleanupObject

Remove extra temp files


52
53
54
55
56
57
# File 'lib/image_optim/handler.rb', line 52

def cleanup
  return unless @dst

  @dst.unlink
  @dst = nil
end

#processObject

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


37
38
39
40
41
42
43
44
45
46
47
48
49
# 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