Class: HK::Router

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

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Router

Returns a new instance of Router.

Yields:

  • (_self)

Yield Parameters:

  • _self (HK::Router)

    the object that the method was called on



5
6
7
8
9
10
# File 'lib/hotchkiss/router.rb', line 5

def initialize
  @routes_by_method = {}
  @routes = []
  yield(self)
  compute
end

Instance Method Details

#bind(path, infos) ⇒ Object



12
13
14
15
16
17
# File 'lib/hotchkiss/router.rb', line 12

def bind(path, infos)
  route = {}
  route[:path] = path
  route = route.merge!(infos)
  @routes << route
end

#match?(env) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
32
33
# File 'lib/hotchkiss/router.rb', line 24

def match?(env)
  method = env['REQUEST_METHOD'].downcase.to_sym
  path = env['REQUEST_PATH'].eql?("/") ? "/" : env['REQUEST_PATH'].gsub(/\/$/, '')
  @routes_by_method[method].each do |route|
    if path.match(route[:regexp])
      return route, extract_params(route, path.scan(route[:regexp]).flatten!)
    end
  end
  return nil, nil
end

#root(infos) ⇒ Object

Raises:

  • (TypeError)


19
20
21
22
# File 'lib/hotchkiss/router.rb', line 19

def root(infos)
  raise TypeError unless infos.is_a?(Hash)
  bind("/", infos)
end