Class: Topiary::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/topiary/node.rb

Overview

Represents one vertex or node in your graph.

Each node may hold some user-defined data, so you can track what they represent.

Nodes also contain a list of "needs" (incoming edges) and "feeds" (outgoing edges). You may pass a list of connected nodes when you instantiate one, but usually you'll need to make your objects first and then add their needs/feeds. (If you didn't have to do that you probably wouldn't need this library, right?)

There are mutator methods you can use like this:

n1 = Node.new "n1"
n2 = Node.new "n2"
n1.need! n2

That will create an edge pointing from n2 to n1.

Once your graph is ready, you can pass the list of nodes to Topiary.sort.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = nil, needs = [], feeds = []) ⇒ Node

Returns a new instance of Node.



25
26
27
28
29
# File 'lib/topiary/node.rb', line 25

def initialize(data=nil, needs=[], feeds=[])
  @data = data
  @needs = Set.new needs
  @feeds = Set.new feeds
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



23
24
25
# File 'lib/topiary/node.rb', line 23

def data
  @data
end

#feedsObject (readonly)

Returns the value of attribute feeds.



23
24
25
# File 'lib/topiary/node.rb', line 23

def feeds
  @feeds
end

#needsObject (readonly)

Returns the value of attribute needs.



23
24
25
# File 'lib/topiary/node.rb', line 23

def needs
  @needs
end

Instance Method Details

#begin!Object



31
32
33
34
35
36
# File 'lib/topiary/node.rb', line 31

def begin!
  @original_needs = @needs
  @original_feeds = @feeds
  @needs = @needs.clone
  @feeds = @feeds.clone
end

#feed!(n) ⇒ Object



53
54
55
56
# File 'lib/topiary/node.rb', line 53

def feed!(n)
  feeds << n
  n.needs << self
end

#inspectObject



72
73
74
# File 'lib/topiary/node.rb', line 72

def inspect
  to_s
end

#nameObject



58
59
60
# File 'lib/topiary/node.rb', line 58

def name
  data && data.to_s || object_id.to_s
end

#need!(n) ⇒ Object



47
48
49
50
51
# File 'lib/topiary/node.rb', line 47

def need!(n)
  @original_needs << n
  needs << n
  n.feeds << self
end

#restore!Object

Since the sorting algorithm mutates the edges, you can call this to restore everything to its original state. The graph still isn't re-entrant, but at least it comes back from sorting the same as it entered.



42
43
44
45
# File 'lib/topiary/node.rb', line 42

def restore!
  @needs = @original_needs
  @feeds = @original_feeds
end

#to_sObject



62
63
64
65
66
67
68
69
70
# File 'lib/topiary/node.rb', line 62

def to_s
  [
    name,
    "needs:",
    "[" + needs.map(&:name).join(", ") + "]",
    "feeds:",
    "[" + feeds.map(&:name).join(", ") + "]"
  ].join(" ")
end