Method: Tickethub::Collection#initialize

Defined in:
lib/tickethub/collection.rb

#initialize(endpoint, klass, params = {}) ⇒ Collection

Returns a new instance of Collection.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/tickethub/collection.rb', line 13

def initialize(endpoint, klass, params = {})
  @params = params.dup
  @endpoint = endpoint
  @klass = klass

  klass.registered_types.each do |type, options|
    define_singleton_method type do
      instance_variable_defined?("@#{type}") ? instance_variable_get("@#{type}") :
        instance_variable_set("@#{type}", Tickethub::Collection.new(endpoint[type], options[:klass]))
    end
  end

  klass.collection_methods.merge(klass.scopes).each do |key, block|
    define_singleton_method key, &block
  end

  super() do |yielder|
    self.reload! if cache.nil?

    cache.each do |row|
      yielder << @klass.call(endpoint, row)
    end

    while (offset + cache.length) < count
      response = endpoint.get params.merge(offset: cache.length)
      response.decoded.each do |row| cache << row
        yielder << @klass.call(endpoint, row)
      end
    end
  end
end