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



12
13
14
15
16
17
18
19
# File 'lib/image_optim/handler.rb', line 12

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



9
10
11
# File 'lib/image_optim/handler.rb', line 9

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



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/image_optim/handler.rb', line 23

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



54
55
56
57
58
59
# File 'lib/image_optim/handler.rb', line 54

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



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/image_optim/handler.rb', line 39

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