Class: Rack::Smusher

Inherits:
Object
  • Object
show all
Includes:
Rake::DSL
Defined in:
lib/rack/smusher.rb

Constant Summary collapse

VERSION =
"0.0.4"

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}, &block) ⇒ Smusher

Returns a new instance of Smusher.



19
20
21
22
23
24
25
26
27
# File 'lib/rack/smusher.rb', line 19

def initialize(app, options = {}, &block)
  @app = app
  @options = {
    :source => "public/images/source",
    :target => "public/images",
    :base_url => "/images/"
  }.merge(options)
  instance_eval(&block) if block_given?
end

Instance Method Details

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rack/smusher.rb', line 29

def call(env)
  status, headers, body = @app.call(env)

  if env['PATH_INFO'][/png/]
    should_compress = false
    source_path = @options[:source] + '/' + (env['PATH_INFO'] - @options[:base_url])
    target_path = @options[:target] + '/' + (env['PATH_INFO'] - @options[:base_url])

    there_is_a_source_file = File.exist?(source_path)
    there_is_a_target_file = File.exist?(target_path)

    if there_is_a_source_file && there_is_a_target_file
      if File.mtime(source_path) > File.mtime(target_path)
        should_compress = true
      end
    end

    if !there_is_a_target_file && there_is_a_source_file
      should_compress = true
    end

    if should_compress
      status, body = compress source_path, target_path
    end
  end

  @response = Rack::Response.new(body, status, headers)
  @response.to_a
end

#compress(source, target) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/rack/smusher.rb', line 59

def compress source, target
  puts "compressing #{source}"
  mkdir_p File.dirname(target), { :verbose => false }
  cp_r source, target, { :verbose => false }
  %x(smusher #{target})
  [200, File.read(target)]
end