8ce8d6aa5690367f7e5c1fca48c5d1a7401f3e95
[arvados.git] / app / models / orvos_resource_list.rb
1 class OrvosResourceList
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 where(cond)
19     cond = cond.dup
20     cond.keys.each do |uuid_key|
21       if cond[uuid_key] and (cond[uuid_key].is_a? Array or
22                              cond[uuid_key].is_a? OrvosBase)
23         # Coerce cond[uuid_key] to an array of uuid strings.  This
24         # allows caller the convenience of passing an array of real
25         # objects and uuids in cond[uuid_key].
26         if !cond[uuid_key].is_a? Array
27           cond[uuid_key] = [cond[uuid_key]]
28         end
29         cond[uuid_key] = cond[uuid_key].collect do |item|
30           if item.is_a? OrvosBase
31             item.uuid
32           else
33             item
34           end
35         end
36       end
37     end
38     cond.keys.select { |x| x.match /_kind$/ }.each do |kind_key|
39       if cond[kind_key].is_a? Class
40         cond = cond.merge({ kind_key => 'orvos#' + $orvos_api_client.class_kind(cond[kind_key]) })
41       end
42     end
43     api_params = {
44       _method: 'GET',
45       where: cond
46     }
47     api_params[:eager] = '1' if @eager
48     api_params[:limit] = @limit if @limit
49     res = $orvos_api_client.api @resource_class, '', api_params
50     @results = $orvos_api_client.unpack_api_response res
51     self
52   end
53
54   def results
55     self.where({}) if !@results
56     @results
57   end
58
59   def all
60     where({})
61   end
62
63   def each(&block)
64     results.each do |m|
65       block.call m
66     end
67     self
68   end
69
70   def |(x)
71     if x.is_a? Hash
72       self.to_hash | x
73     else
74       results | x.to_ary
75     end
76   end
77
78   def to_ary
79     results
80   end
81
82   def to_hash
83     Hash[results.collect { |x| [x.uuid, x] }]
84   end
85 end