Class: Mailchimp::Collection

Inherits:
Array
  • Object
show all
Includes:
Paging
Defined in:
lib/mailchimp_api_v3/collection.rb,
lib/mailchimp_api_v3/collection/paging.rb

Defined Under Namespace

Modules: Paging

Constant Summary

Constants included from Paging

Paging::DEFAULT_PAGE_SIZE

Instance Method Summary collapse

Methods included from Paging

#fetch_options, #find_each, #find_in_pages, #invalidate_current_page, #offset, #page, #page_array, #page_children, #page_size, #parse_options

Constructor Details

#initialize(client, parent_path = '', options = {}) ⇒ Collection

Returns a new instance of Collection.



6
7
8
9
10
11
12
# File 'lib/mailchimp_api_v3/collection.rb', line 6

def initialize(client, parent_path = '', options = {})
  @client = client
  @parent_path = parent_path

  parse_options(options)
  super page_children
end

Instance Method Details

#countObject



14
15
16
# File 'lib/mailchimp_api_v3/collection.rb', line 14

def count
  page['total_items']
end

#create(data) ⇒ Object



40
41
42
43
# File 'lib/mailchimp_api_v3/collection.rb', line 40

def create(data)
  response = @client.post data, path
  self.class::CHILD_CLASS.new @client, response, path
end

#find_by(data) ⇒ Object



35
36
37
38
# File 'lib/mailchimp_api_v3/collection.rb', line 35

def find_by(data)
  instances = where(data, 1)
  instances ? instances.first : nil
end

#first_or_create(data) ⇒ Object



45
46
47
48
49
# File 'lib/mailchimp_api_v3/collection.rb', line 45

def first_or_create(data)
  instance = find_by(data)
  return instance if instance
  create(data)
end

#pathObject



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

def path
  @path ||= "#{@parent_path}/#{self.class::PATH_KEY}"
end

#where(data, limit = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mailchimp_api_v3/collection.rb', line 22

def where(data, limit = nil)
  instances = []

  find_each do |instance|
    if instance.matches? data
      instances << instance
      break if instances.count == limit
    end
  end

  instances
end