Class: Oldskool::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/oldskool/router.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Router

Returns a new instance of Router.



3
4
5
# File 'lib/oldskool/router.rb', line 3

def initialize(config)
  @config = config
end

Instance Method Details

#error(msg) ⇒ Object



7
8
9
# File 'lib/oldskool/router.rb', line 7

def error(msg)
  Oldskool::ErrorHandler.new({}, {:type => :error, :msg => msg}, @config).handle_request(nil, nil)
end

#route(params) ⇒ Object



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
# File 'lib/oldskool/router.rb', line 11

def route(params)
  defaulting = false

  k = ""
  q = params[:q].strip

  if params[:q] =~ /^(\w+?)(\s.+)*$/
    k = $1.downcase
    q = $2.strip rescue ""
  end

  default = nil
  handler = nil

  @config[:keywords].each do |keyword|
    default = keyword if [keyword[:keywords]].flatten.include?(:default)

    handler = keyword if [keyword[:keywords]].flatten.include?(k)

    break if handler
  end

  if (!handler && default)
    defaulting = true
    handler = default
  elsif !handler
    return error("No handler for keyword #{k} found and no default handler specified")
  end

  handler_class = "%sHandler" % [handler[:type].to_s.capitalize]

  if Oldskool.constants.map{|k| k.to_s}.include?(handler_class)
    if defaulting
      Oldskool.const_get(handler_class).new(params, handler, @config).handle_request("", params[:q])
    else
      Oldskool.const_get(handler_class).new(params, handler, @config).handle_request(k, q)
    end
  else
    return error("Do not know how to handle type %s keywords" % [ handler[:type] ])
  end
end