Class: Faye::Channel::Tree

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/faye/channel.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = nil) ⇒ Tree

Returns a new instance of Tree.



56
57
58
59
# File 'lib/faye/channel.rb', line 56

def initialize(value = nil)
  @value = value
  @children = {}
end

Instance Attribute Details

#valueObject

Returns the value of attribute value.



54
55
56
# File 'lib/faye/channel.rb', line 54

def value
  @value
end

Instance Method Details

#[](name) ⇒ Object



70
71
72
73
# File 'lib/faye/channel.rb', line 70

def [](name)
  subtree = traverse(name)
  subtree ? subtree.value : nil
end

#[]=(name, value) ⇒ Object



75
76
77
78
# File 'lib/faye/channel.rb', line 75

def []=(name, value)
  subtree = traverse(name, true)
  subtree.value = value unless subtree.nil?
end

#each(prefix = []) {|prefix, @value| ... } ⇒ Object

Yields:



65
66
67
68
# File 'lib/faye/channel.rb', line 65

def each(prefix = [], &block)
  each_child { |path, subtree| subtree.each(prefix + [path], &block) }
  yield(prefix, @value) unless @value.nil?
end

#each_childObject



61
62
63
# File 'lib/faye/channel.rb', line 61

def each_child
  @children.each { |key, subtree| yield(key, subtree) }
end

#glob(path = []) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/faye/channel.rb', line 93

def glob(path = [])
  path = Channel.parse(path) if String === path
  
  return [] if path.nil?
  return @value.nil? ? [] : [@value] if path.empty?
  
  if path == [:*]
    return @children.inject([]) do |list, (key, subtree)|
      list << subtree.value unless subtree.value.nil?
      list
    end
  end
  
  if path == [:**]
    list = map { |key, value| value }
    list.pop unless @value.nil?
    return list
  end
  
  list = @children.values_at(path.first, :*).
                   compact.
                   map { |t| t.glob(path[1..-1]) }
  
  list << @children[:**].value if @children[:**]
  list.flatten
end

#traverse(path, create_if_absent = false) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/faye/channel.rb', line 80

def traverse(path, create_if_absent = false)
  path = Channel.parse(path) if String === path
  
  return nil if path.nil?
  return self if path.empty?
  
  subtree = @children[path.first]
  return nil if subtree.nil? and not create_if_absent
  subtree = @children[path.first] = self.class.new if subtree.nil?
  
  subtree.traverse(path[1..-1], create_if_absent)
end