Class: Bats

Inherits:
Object
  • Object
show all
Extended by:
Wizarding
Defined in:
lib/bats.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.addRoute(m, p, o = nil, &b) ⇒ Object



14
15
16
17
18
# File 'lib/bats.rb', line 14

def self.addRoute m, p, o = nil, &b
	@traits[:routes] ||= {}
	@traits[:routes][m] ||= {}
	@traits[:routes][m][p] = (block_given?) ? b : o
end

.call(env) ⇒ Object



39
# File 'lib/bats.rb', line 39

def self.call env; new.call(env); end

.inherited(c) ⇒ Object



10
11
12
# File 'lib/bats.rb', line 10

def self.inherited c
	c.traits(*traits.keys)
end

.redirect(l, isTemporary = true) ⇒ Object



26
27
28
29
# File 'lib/bats.rb', line 26

def self.redirect l, isTemporary = true
	i = (isTemporary) ? '307' : '301'
	s(i).headers("Location" => l)
end

.s(i) ⇒ Object



31
32
33
# File 'lib/bats.rb', line 31

def self.s i
	Class.new(::HTTPResponse.const_get("Status#{i}"))
end

Instance Method Details

#call(env) ⇒ Object



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
67
68
69
70
71
72
73
74
75
# File 'lib/bats.rb', line 40

def call env
	method = env['REQUEST_METHOD'].downcase.to_sym
	path = env['PATH_INFO']
	matches ||= nil
	if @routes && @routes[method] then
		if @routes[method].include?(path) then
			route = @routes[method][path]
		else
			@routes[method].each do | p, b |
				if p.kind_of?(Regexp) then
					if matches = path.match(p) then
						matches = matches[1, matches.length - 1]
						matches.map! do | i | 
							i = (i) ? i : ''
							i = i.to_i if i =~ /^\d+$/
							i
						end
						route = b
						break # Eh! give me a break here!
					end
				end
			end
		end
	end
	route ||= s(404)
	args = (matches) ? [env, *matches] : [env]
	begin
		route = route.call(*args) if route.kind_of?(Proc)
		route.call(env)
	rescue
		b = '<h1>Ooops... The code broke.</h1>'
		b += "<h3>#{$!.to_s}</h3>#{$!.backtrace.join('<br/>')}"
		route = s(500).body b
		route.call(env)
	end
end

#s(i) ⇒ Object



35
36
37
# File 'lib/bats.rb', line 35

def s i
	Class.new(::HTTPResponse.const_get("Status#{i}"))
end