public
Description: The invisible framework
Homepage: http://macournoyer.com/
Clone URL: git://github.com/macournoyer/invisible.git
macournoyer (author)
Sat Jul 19 20:57:12 -0700 2008
commit  4a00c623562bceaa74b78f24bb9af9bde97311e2
tree    083262d744878fd811b2e228a6ecfdc9ea349675
parent  b038e8526a54cd0cbc66aa8968429c76479a17b2
invisible / invisible.rb
100644 54 lines (44 sloc) 1.251 kb
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
require "rubygems"
require "thin"
require "markaby"
 
class Invisible
  def initialize(&block)
    @actions = []
    @layouts = {}
    instance_eval(&block)
  end
  
  def process(method, route, &block)
    @actions << [method.to_s, route, block]
  end
  def get(route, &b); process("get", route, &b) end
  def post(route, &b); process("post", route, &b) end
  
  def render(status=200, options_and_headers={}, &block)
    layout = @layouts[options_and_headers.delete(:layout) || :default]
    content = Markaby::Builder.new.capture(&block)
    content = Markaby::Builder.new({ :content => content }, nil, &layout).to_s
    [status, options_and_headers, content]
  end
  
  def layout(name=:default, &block)
    @layouts[name] = block
  end
  
  def call(env)
    params = nil
    action = @actions.detect { |method, route, _| env["REQUEST_METHOD"].downcase == method && params = env["PATH_INFO"].match(route) }
    
    if action
      action.last.call(*params[1..-1])
    else
      [404, {}, "Not found"]
    end
  end
  
  def run(*args)
    app = self
    Thin::Server.start(*args) do
      use Rack::ShowExceptions
      use Rack::CommonLogger
      run app
    end
  end
  
  def self.run(*args, &block)
    new(&block).run(*args)
  end
end