Class: ProtobufDescriptor::NamedCollection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/protobuf_descriptor/named_collection.rb

Overview

Array wrapper that also supports lookup by "name"

By default all members must respond to name, but this behavior can be overriden by passing a block in the initializer.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, &matcher) ⇒ NamedCollection

Returns a new instance of NamedCollection.



16
17
18
19
20
21
22
23
24
25
# File 'lib/protobuf_descriptor/named_collection.rb', line 16

def initialize(collection, &matcher)
  @collection = []
  collection.each { |c| @collection << c }

  if block_given?
    @matcher = matcher
  else
    @matcher = lambda { |name, member| return member.name == name }
  end
end

Instance Attribute Details

#collectionObject

Returns the value of attribute collection.



9
10
11
# File 'lib/protobuf_descriptor/named_collection.rb', line 9

def collection
  @collection
end

#matcherObject

Returns the value of attribute matcher.



9
10
11
# File 'lib/protobuf_descriptor/named_collection.rb', line 9

def matcher
  @matcher
end

Instance Method Details

#[](index) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/protobuf_descriptor/named_collection.rb', line 27

def [](index)
  if Fixnum === index
    return collection[index]
  else
    return find_by_name(index)
  end
end

#find_by_name(name) ⇒ Object



35
36
37
38
39
# File 'lib/protobuf_descriptor/named_collection.rb', line 35

def find_by_name(name)
  return collection.find { |member|
    matcher.call(name.to_s, member)
  }
end

#to_aObject



41
42
43
# File 'lib/protobuf_descriptor/named_collection.rb', line 41

def to_a
  return self.collection.to_a
end