Class: PagerJudy::API::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/pager_judy/api/collection.rb

Overview

Represents a collection of things, e.g. services, users, …

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, type, criteria = {}) ⇒ Collection

Returns a new instance of Collection.



10
11
12
13
14
# File 'lib/pager_judy/api/collection.rb', line 10

def initialize(resource, type, criteria = {})
  @resource = resource
  @type = type
  @criteria = criteria
end

Instance Attribute Details

#criteriaObject (readonly)

Returns the value of attribute criteria.



18
19
20
# File 'lib/pager_judy/api/collection.rb', line 18

def criteria
  @criteria
end

#resourceObject (readonly)

Returns the value of attribute resource.



16
17
18
# File 'lib/pager_judy/api/collection.rb', line 16

def resource
  @resource
end

#typeObject (readonly)

Returns the value of attribute type.



17
18
19
# File 'lib/pager_judy/api/collection.rb', line 17

def type
  @type
end

Instance Method Details

#[](id) ⇒ Object



44
45
46
# File 'lib/pager_judy/api/collection.rb', line 44

def [](id)
  Item.new(resource.subresource(id), item_type, id)
end

#create(data) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/pager_judy/api/collection.rb', line 48

def create(data)
  name = data.fetch("name")
  if dry_run?
    result = data.merge("id" => "{#{name}}")
  else
    result = resource.post(item_type => data).fetch(item_type)
  end
  id = result.fetch("id")
  logger.info { "created #{item_type} #{name.inspect} [#{id}]" }
  result
end

#create_or_update(id, data) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/pager_judy/api/collection.rb', line 60

def create_or_update(id, data)
  if id.nil?
    create(data)
  else
    self[id].update(data)
  end
end

#create_or_update_by_name(name, data) ⇒ Object



72
73
74
# File 'lib/pager_judy/api/collection.rb', line 72

def create_or_update_by_name(name, data)
  create_or_update(id_for_name(name), data.merge("name" => name))
end

#eachObject



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pager_judy/api/collection.rb', line 31

def each
  offset = 0
  loop do
    data = resource.get(criteria.merge(offset: offset, limit: 100))
    data.fetch(type).each do |item|
      yield item
    end
    break unless data["more"]
    offset = data.fetch("offset") + data.fetch("limit")
  end
  self
end

#id_for_name(name) ⇒ Object



68
69
70
# File 'lib/pager_judy/api/collection.rb', line 68

def id_for_name(name)
  ids_by_name[name]
end

#item_typeObject



20
21
22
# File 'lib/pager_judy/api/collection.rb', line 20

def item_type
  type.sub(/ies$/, "y").chomp("s")
end

#with(more_criteria) ⇒ Object



26
27
28
29
# File 'lib/pager_judy/api/collection.rb', line 26

def with(more_criteria)
  more_criteria = Hash[more_criteria.select { |_, v| v }]
  Collection.new(resource, type, criteria.merge(more_criteria))
end