Class: Harbor::Router

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

Defined Under Namespace

Classes: Using

Constant Summary collapse

URI_CHAR =
'[^/?:,&#\.\[\]]'.freeze
PARAM =
/(:(#{URI_CHAR}+))/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&routes) ⇒ Router

Returns a new instance of Router.


9
10
11
12
13
# File 'lib/harbor/router.rb', line 9

def initialize(&routes)
  @routes = []
  @route_match_cache = {}
  instance_eval(&routes) if block_given?
end

Instance Attribute Details

#routesObject

Returns the value of attribute routes.


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

def routes
  @routes
end

Instance Method Details

#clearObject


76
77
78
# File 'lib/harbor/router.rb', line 76

def clear
  @routes = []
end

#delete(matcher, &handler) ⇒ Object

Matches a DELETE request


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

def delete(matcher, &handler)
  register(:delete, matcher, &handler)
end

#get(matcher, &handler) ⇒ Object

Matches a GET request


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

def get(matcher, &handler)
  register(:get, matcher, &handler)
end

#match(request) ⇒ Object


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/harbor/router.rb', line 80

def match(request)
  @routes.each do |request_method, matcher, param_keys, handler|
    next unless request.request_method == request_method

    # Strip trailing forward-slash on request path before matching
    request_path = (request.path_info[-1] == ?/) ? request.path_info[0..-2] : request.path_info

    next unless request_path =~ matcher

    request.params.update(Hash[*param_keys.zip($~.captures).flatten])
    return handler
  end

  # No routes matched, so return false
  false
end

#merge!(other) ⇒ Object


15
16
17
# File 'lib/harbor/router.rb', line 15

def merge!(other)
  self.routes |= other.routes
end

#post(matcher, &handler) ⇒ Object

Matches a POST (create) request


25
26
27
# File 'lib/harbor/router.rb', line 25

def post(matcher, &handler)
  register(:post, matcher, &handler)
end

#put(matcher, &handler) ⇒ Object

Matches a PUT (update) request


30
31
32
# File 'lib/harbor/router.rb', line 30

def put(matcher, &handler)
  register(:put, matcher, &handler)
end

#register(request_method, matcher, &handler) ⇒ Object


69
70
71
72
73
74
# File 'lib/harbor/router.rb', line 69

def register(request_method, matcher, &handler)
  matcher, param_keys = transform(matcher)
  route = [request_method.to_s.upcase, matcher, param_keys, handler]
  @routes << route
  route
end

#using(container, klass, initializer = nil, &block) ⇒ Object


39
40
41
# File 'lib/harbor/router.rb', line 39

def using(container, klass, initializer = nil, &block)
  self.class::Using.new(self, container, klass, initializer).instance_eval(&block)
end