Class: Router
- Inherits:
-
Object
- Object
- Router
- Defined in:
- lib/simple_gate/router.rb
Instance Attribute Summary collapse
-
#paths ⇒ Object
Graph of server connections.
Instance Method Summary collapse
-
#find(start, target, current_route = []) ⇒ Array?
A simple recursive pathfinder.
-
#initialize(paths = {}) ⇒ Router
constructor
Create a new Router for a network of interconnected servers.
Constructor Details
#initialize(paths = {}) ⇒ Router
Create a new Router for a network of interconnected servers. An example connections graph with three servers ‘foo’, ‘bar’ and ‘baz’:
router = Router.new
# Define a graph: foo -> bar -> baz
router.paths = {
'foo' => %w[bar],
'bar' => %w[baz]
}
router.find('foo', 'baz') #=> ['foo', 'bar', 'baz']
19 20 21 |
# File 'lib/simple_gate/router.rb', line 19 def initialize(paths={}) @paths = paths end |
Instance Attribute Details
#paths ⇒ Object
Graph of server connections.
3 4 5 |
# File 'lib/simple_gate/router.rb', line 3 def paths @paths end |
Instance Method Details
#find(start, target, current_route = []) ⇒ Array?
A simple recursive pathfinder. Uses a very naieve depth-first recursive full-graph search to find the shortest route.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/simple_gate/router.rb', line 31 def find(start, target, current_route = []) return [target] if start == target return nil unless paths.has_key?(start) # Map all possible paths to the target. # Skip nodes we have already visited next_nodes = paths[start] - current_route routes = next_nodes.map do |next_node| find(next_node, target, current_route + [start]) end # Reduce the collection to the shortest path shortest_route = routes.compact.inject(nil) {|shortest,possibility| next possibility if shortest.nil? possibility.size < shortest.size ? possibility : shortest } return [start] + shortest_route if shortest_route nil end |