Class: Rod::Rest::CollectionProxy

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/rod/rest/collection_proxy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(proxy, association_name, size, client) ⇒ CollectionProxy

Initializes a CollectionProxy.

  • :proxy - the object this collection belongs to

  • :association_name - the name of proxie’s plural association this collection is returned for

  • :size - the size of the collection

  • :client - the REST API client



14
15
16
17
18
19
20
# File 'lib/rod/rest/collection_proxy.rb', line 14

def initialize(proxy,association_name,size,client)
  @proxy = proxy
  @association_name = association_name
  @size = size
  @client = client
  @cache = []
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



7
8
9
# File 'lib/rod/rest/collection_proxy.rb', line 7

def size
  @size
end

Instance Method Details

#[](index) ⇒ Object

Returns the index-th element of the collection.



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rod/rest/collection_proxy.rb', line 39

def [](index)
  begin
    if Range === index
      @cache[index] = @client.fetch_related_objects(@proxy,@association_name,index)
    else
      return @cache[index] unless @cache[index].nil?
      @cache[index] = @client.fetch_related_object(@proxy,@association_name,index)
    end
  rescue MissingResource
    nil
  end
end

#eachObject

Iterates over the elements of the collection.



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rod/rest/collection_proxy.rb', line 63

def each
  if block_given?
    if @size > 0
      self[0..@size-1].each do |object|
        yield object
      end
    end
  else
    enum_for(:each)
  end
end

#empty?Boolean

Returns true if the collection is empty (i.e. its size == 0).

Returns:

  • (Boolean)


34
35
36
# File 'lib/rod/rest/collection_proxy.rb', line 34

def empty?
  self.size == 0
end

#firstObject

Returns the first element of the collection.



53
54
55
# File 'lib/rod/rest/collection_proxy.rb', line 53

def first
  self.size > 0 ? self[0] : nil
end

#inspectObject

Detailed description of the object, i.e. Rod::Rest::CollectionProxy<Car#drivers>



24
25
26
# File 'lib/rod/rest/collection_proxy.rb', line 24

def inspect
  "#{self.class.name}<#{@proxy.type}\##{@association_name}[#{@size}]>"
end

#lastObject

Returns the last element of the collection.



58
59
60
# File 'lib/rod/rest/collection_proxy.rb', line 58

def last
  self.size > 0 ? self[size - 1] : nil
end

#to_sObject

Short description of the collection, i.e. [5-elements].



29
30
31
# File 'lib/rod/rest/collection_proxy.rb', line 29

def to_s
  "[#{@size}-elements]"
end