Class: Whisper::Router

Inherits:
Object
  • Object
show all
Includes:
Loggy
Defined in:
lib/whisper/router.rb

Overview

nothing special. maintains a list of handlers, translates from paths to content, and from url descriptions to urls

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Router

Returns a new instance of Router.



11
12
13
14
15
16
# File 'lib/whisper/router.rb', line 11

def initialize root
  root = root.sub(/\/$/, "")
  @root_re = /^#{Regexp.escape root}/
  @handlers = []
  @handlers_by_route = {}
end

Instance Attribute Details

#handlersObject (readonly)

Returns the value of attribute handlers.



18
19
20
# File 'lib/whisper/router.rb', line 18

def handlers
  @handlers
end

Instance Method Details

#add_handler(route, request_method, path, &block) ⇒ Object



20
21
22
23
24
# File 'lib/whisper/router.rb', line 20

def add_handler route, request_method, path, &block
  handler = Handler.new request_method, path, &block
  @handlers_by_route[route] = handler
  @handlers << [handler, route]
end

#expire!Object



26
# File 'lib/whisper/router.rb', line 26

def expire!; @handlers.each { |h| h.expire! } end

#get_content_for(path, params, request_method) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/whisper/router.rb', line 28

def get_content_for path, params, request_method
  path = path.sub @root_re, ""
  case(result = @handlers.argfind { |h, route| h.handle path, params, request_method, route })
  when nil, :invalid; nil # a handler matched but didn't like the request
  when Array; result
  else
    result.refresh!
    begin
      [result.content, result.content_type]
    rescue InvalidPageError => e
      nil
    end
  end
end

#url_for(opts = {}) ⇒ Object



43
44
45
46
47
# File 'lib/whisper/router.rb', line 43

def url_for opts={}
  route = opts[:route] or raise ArgumentError, "no :route specified"
  handler = @handlers_by_route[opts[:route]] or raise ArgumentError, "no such route: #{route.inspect} (have #{@handlers_by_route.keys.join(', ')})"
  handler.url_for opts
end