Class: Lennarb::RouteNode

Inherits:
Object
  • Object
show all
Defined in:
lib/lennarb/route_node.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouteNode

Initialize the route node



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

def initialize
	@children  = {}
	@blocks    = {}
	@param_key = nil
end

Instance Attribute Details

#blocksObject

Returns the value of attribute blocks.



8
9
10
# File 'lib/lennarb/route_node.rb', line 8

def blocks
  @blocks
end

#childrenObject

Returns the value of attribute children.



8
9
10
# File 'lib/lennarb/route_node.rb', line 8

def children
  @children
end

#param_keyObject

Returns the value of attribute param_key.



8
9
10
# File 'lib/lennarb/route_node.rb', line 8

def param_key
  @param_key
end

Instance Method Details

#add_route(parts, http_method, block) ⇒ void

This method returns an undefined value.

Add a route to the route node



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/lennarb/route_node.rb', line 28

def add_route(parts, http_method, block)
	current_node = self

	parts.each do |part|
		if part.start_with?(':')
			key = :param
			current_node.children[key] ||= RouteNode.new
			current_node = current_node.children[key]
			current_node.param_key = part[1..].to_sym
		else
			key = part
			current_node.children[key] ||= RouteNode.new
			current_node = current_node.children[key]
		end
	end

	current_node.blocks[http_method] = block
end

#match_route(parts, http_method) ⇒ Array

Match a route to the route node

Returns:

  • (Array)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/lennarb/route_node.rb', line 54

def match_route(parts, http_method)
	current_node = self
	params = {}

	parts.each do |part|
		return [nil, nil] unless current_node.children.key?(part) || current_node.children[:param]

		if current_node.children.key?(part)
			current_node = current_node.children[part]
		else
			param_node = current_node.children[:param]
			params[param_node.param_key] = part
			current_node = param_node
		end
	end

	[current_node.blocks[http_method], params]
end