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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/restfully/collection.rb', line 36

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)


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

def empty?
  total == 0
end

#expandObject

Expand the items that



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

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

#find_by_index(index) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/restfully/collection.rb', line 28

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
23
24
25
26
# File 'lib/restfully/collection.rb', line 18

def find_by_uid(symbol)
  direct_uri = media_type.direct_fetch_uri(symbol)
  # Attempt to make a direct fetch if possible (in case of large collections)
  found = session.get(direct_uri) if direct_uri
  # Fall back to collection traversal if direct fetch was not possible, or was not found
  found = find{ |i| i.media_type.represents?(symbol) } if found.nil?
  found.expand unless found.nil?
  found
end

#inspectObject



84
85
86
# File 'lib/restfully/collection.rb', line 84

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

#lastObject



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

def last
  self[-1]
end

#lengthObject



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

def length
  self["items"].length
end

#offsetObject



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

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

#totalObject



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

def total
  self["total"].to_i
end