Module: Bitmovin::ChildCollection::ClassMethods

Defined in:
lib/bitmovin/child_collection.rb

Instance Method Summary collapse

Instance Method Details

#child_collection(name, path, parameters, klass) ⇒ Object



8
9
10
11
12
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
# File 'lib/bitmovin/child_collection.rb', line 8

def child_collection(name, path, parameters, klass)
  define_method("load_#{name}") do
    vars = parameters.map { |p| instance_variable_get("@#{p}") }
    url = path % vars
    response = Bitmovin.client.get(url)

    result(response)["items"].map do |item| 
      p = vars + [item]
      klass.new(*p)
    end
  end
  define_method(name) do
    if !persisted?
      raise "#{self.class.name.demodulize} is not persisted yet - can't load #{name}"
    end
    if instance_variable_get("@#{name}").nil?
      items = send("load_#{name}")
      instance_variable_set("@#{name}", items)
    end
    instance_variable_get("@#{name}")
  end

  define_method("build_#{ActiveSupport::Inflector.singularize(name)}") do |hash = {}|
    instance_vars = parameters.map { |p| instance_variable_get("@#{p}") }
    if !persisted?
      raise "Period is not persisted yet - can't create #{ActiveSupport::Inflector.singularize(name)}"
    end
    instance_vars << hash
    klass.new(*instance_vars)
  end
end