shinzui (owner)

Fork Of

gist: 206896 by josh CodeRack middleware example...

Revisions

gist: 214739 Download_button fork
public
Description:
Rack route decoupling example using the rack sparklines middleware
Public Clone URL: git://gist.github.com/214739.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Example from Rick Olson's Sparklines middleware
# http://github.com/technoweenie/rack-sparklines/blob/master/lib/rack-sparklines.rb
module Rack
  class Sparklines
    def initialize(app, options = {})
      @app, @options = app, options
    end
 
    def call(env)
      if env['PATH_INFO'][@options[:prefix]] == @options[:prefix]
        @data_path = env['PATH_INFO'][@options[:prefix].size+1..-1]
        @data_path.sub! /\.png$/, ''
        @png_path = @data_path + ".png"
        @cache_file = ::File.join(@options[:directory], @png_path)
        # ...
       [200, {
          "Last-Modified" => ::File.mtime(@cache_file).rfc822,
          "Content-Type" => "image/png",
          "Content-Length" => ::File.size(@cache_file).to_s
        }, self]
      else
        @app.call(env)
      end
    end
  end
end
 
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Refactored to decouple rack app from routing concern
module Rack
  class Sparklines
    def initialize(options = {})
      @options = options
    end
 
    def call(env)
       data_path = env['PATH_INFO']
       data_path.sub! /\.png$/, ''
       png_path = data_path + ".png"
       cache_file = ::File.join(@options[:directory], png_path)
       # ...
      [200, {
         "Last-Modified" => ::File.mtime(cache_file).rfc822,
         "Content-Type" => "image/png",
         "Content-Length" => ::File.size(cache_file).to_s
       }, self]
    end
 
    class Mapping
      def initialize(app, options = {})
        @app, @prefix = app, /^#{options.delete(:prefix)}/
        @sparklines = Sparklines.new(options)
      end
 
      def call(env)
        if env['PATH_INFO'] =~ @prefix
          env['PATH_INFO'] = env['PATH_INFO'].gsub(@prefix, '')
          @sparklines.call(env)
        else
          @app.call(env)
        end
      end
    end
  end
end
 
# Use as a middleware
use Rack::Sparklines::Mapping, :prefix => "/sparks", :directory => 'data'
 
# Or use with map or any standard rack router
map '/sparks', Rack::Sparklines.new(:directory => 'data')
map '/', Sinatra::Application