Module: Restfully::Collection

Includes:
Enumerable
Defined in:
lib/restfully/collection.rb

Instance Method Summary collapse

Instance Method Details

#[](property) ⇒ Object

If property is a Symbol, it tries to find the corresponding item in the collection. Else, returns the result of calling [] on its superclass.



7
8
9
10
11
12
13
14
15
16
# File 'lib/restfully/collection.rb', line 7

def [](property)
  case property
  when Symbol
    find_by_uid(property)
  when Integer
    find_by_index(property)
  else
    super(property)
  end
end

#each(*args, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/restfully/collection.rb', line 32

def each(*args, &block)
  @items ||= {}
  media_type.each(*args) do |item_media_type|
    hash = item_media_type.hash
    unless @items.has_key?(hash)
      self_link = item_media_type.links.find{|l| l.self?}

      req = HTTP::Request.new(session, :get, self_link.href, :head => {
        'Accept' => self_link.types[0]
      })

      res = HTTP::Response.new(session, 200, {
        'Content-Type' => self_link.types[0]
      }, item_media_type.io)

      @items[hash] = Resource.new(session, res, req).load
    end
    block.call @items[hash]
  end
  self
end

#empty?Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/restfully/collection.rb', line 70

def empty?
  total == 0
end

#expandObject

Expand the items that



75
76
77
78
# File 'lib/restfully/collection.rb', line 75

def expand
  each {|i| i.expand}
  self
end

#find_by_index(index) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/restfully/collection.rb', line 24

def find_by_index(index)
  index = index+length if index < 0
  each_with_index{|item, i|
    return item.expand if i == index
  }
  nil
end

#find_by_uid(symbol) ⇒ Object



18
19
20
21
22
# File 'lib/restfully/collection.rb', line 18

def find_by_uid(symbol)
  found = find{ |i| i.media_type.represents?(symbol) }
  found.expand unless found.nil?
  found
end

#inspectObject



80
81
82
# File 'lib/restfully/collection.rb', line 80

def inspect
  map{|item| item}.inspect
end

#lastObject



66
67
68
# File 'lib/restfully/collection.rb', line 66

def last
  self[-1]
end

#lengthObject



54
55
56
# File 'lib/restfully/collection.rb', line 54

def length
  self["items"].length
end

#offsetObject



62
63
64
# File 'lib/restfully/collection.rb', line 62

def offset
  (self["offset"] || 0).to_i
end

#totalObject



58
59
60
# File 'lib/restfully/collection.rb', line 58

def total
  self["total"].to_i
end