File: middleware_compiler.rb

package info (click to toggle)
libinnate-ruby 2010.07-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 812 kB
  • ctags: 621
  • sloc: ruby: 4,242; makefile: 2
file content (66 lines) | stat: -rw-r--r-- 1,435 bytes parent folder | download
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
module Innate
  class MiddlewareCompiler
    COMPILED = {}

    def self.build(name, &block)
      COMPILED[name] ||= new(name, &block)
    end

    def self.build!(name, &block)
      COMPILED[name] = new(name, &block)
    end

    attr_reader :middlewares, :name

    def initialize(name)
      @name = name.to_sym
      @middlewares = []
      @compiled = nil
      yield(self) if block_given?
    end

    def use(middleware, *args, &block)
      @middlewares << [middleware, args, block]
    end

    def apps(*middlewares)
      @middlewares.concat(middlewares.map{|mw| [mw, [], nil]})
    end

    def run(app)
      @app = app
    end

    def cascade(*apps)
      @app = Rack::Cascade.new(apps)
    end

    # Default application for Innate
    def innate(app = Innate::DynaMap, options = Innate.options)
      roots, publics = options[:roots], options[:publics]

      joined = roots.map{|root| publics.map{|public| ::File.join(root, public)}}

      apps = joined.flatten.map{|public_root| Rack::File.new(public_root) }
      apps << Current.new(Route.new(app), Rewrite.new(app))

      cascade(*apps)
    end

    def call(env)
      compile
      @compiled.call(env)
    end

    def compile
      @compiled ? self : compile!
    end

    def compile!
      @compiled = @middlewares.reverse.
        inject(@app){|app, (middleware, args, block)|
          middleware.new(app, *args, &block) }
      self
    end
  end
end