Removed head_kind and tail_kind from workbench.
[arvados.git] / apps / workbench / app / models / arvados_resource_list.rb
1 class ArvadosResourceList
2   include Enumerable
3
4   def initialize(resource_class)
5     @resource_class = resource_class
6   end
7
8   def eager(bool=true)
9     @eager = bool
10     self
11   end
12
13   def limit(max_results)
14     @limit = max_results
15     self
16   end
17
18   def offset(skip)
19     @offset = skip
20     self
21   end
22
23   def order(orderby_spec)
24     @orderby_spec = orderby_spec
25     self
26   end
27
28   def where(cond)
29     cond = cond.dup
30     cond.keys.each do |uuid_key|
31       if cond[uuid_key] and (cond[uuid_key].is_a? Array or
32                              cond[uuid_key].is_a? ArvadosBase)
33         # Coerce cond[uuid_key] to an array of uuid strings.  This
34         # allows caller the convenience of passing an array of real
35         # objects and uuids in cond[uuid_key].
36         if !cond[uuid_key].is_a? Array
37           cond[uuid_key] = [cond[uuid_key]]
38         end
39         cond[uuid_key] = cond[uuid_key].collect do |item|
40           if item.is_a? ArvadosBase
41             item.uuid
42           else
43             item
44           end
45         end
46       end
47     end
48     cond.keys.select { |x| x.match /_kind$/ }.each do |kind_key|
49       if cond[kind_key].is_a? Class
50         cond = cond.merge({ kind_key => 'arvados#' + $arvados_api_client.class_kind(cond[kind_key]) })
51       end
52     end
53     api_params = {
54       _method: 'GET',
55       where: cond
56     }
57     api_params[:eager] = '1' if @eager
58     api_params[:limit] = @limit if @limit
59     api_params[:offset] = @offset if @offset
60     api_params[:order] = @orderby_spec if @orderby_spec
61     res = $arvados_api_client.api @resource_class, '', api_params
62     @results = $arvados_api_client.unpack_api_response res
63     self
64   end
65
66   def results
67     self.where({}) if !@results
68     @results
69   end
70
71   def results=(r)
72     @results = r
73   end
74
75   def all
76     where({})
77   end
78
79   def each(&block)
80     results.each do |m|
81       block.call m
82     end
83     self
84   end
85
86   def first
87     results.first
88   end
89
90   def last
91     results.last
92   end
93
94   def [](*x)
95     results.send('[]', *x)
96   end
97
98   def |(x)
99     if x.is_a? Hash
100       self.to_hash | x
101     else
102       results | x.to_ary
103     end
104   end
105
106   def to_ary
107     results
108   end
109
110   def to_hash
111     Hash[results.collect { |x| [x.uuid, x] }]
112   end
113
114   def empty?
115     results.empty?
116   end
117
118   def items_available
119     results.items_available if results.respond_to? :items_available
120   end
121
122   def result_limit
123     results.limit if results.respond_to? :limit
124   end
125
126   def result_offset
127     results.offset if results.respond_to? :offset
128   end
129
130 end