Class: Effective::MailchimpCategory

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/effective/mailchimp_category.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.sync!(api: EffectiveMailchimp.api) ⇒ Object

Reads all the InterestCategories from Mailchimp and creates local MailchimpCategory records This is part of the Sync changes from Mailchimp button



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'app/models/effective/mailchimp_category.rb', line 30

def self.sync!(api: EffectiveMailchimp.api)
  # For every mailchimp_list, get all the categories
  mailchimp_lists = Effective::MailchimpList.all

  mailchimp_lists.each do |mailchimp_list|
    # All the Groups from Mailchimp
    categories = api.categories(mailchimp_list.mailchimp_id)

    # Get all our existing Effective::MailchimpCategory records
    mailchimp_categories = where(mailchimp_list: mailchimp_list)

    # Find or create Effective::MailchimpGroups based on existing groups
    categories.each do |category|
      mailchimp_id = category['id']
      mailchimp_category = mailchimp_categories.find { |mc| mc.mailchimp_id == mailchimp_id } || new()

      mailchimp_category.assign_attributes(
        mailchimp_list: mailchimp_list,

        mailchimp_id: mailchimp_id,
        list_id: category['list_id'],
        list_name: mailchimp_list.name,
        name: (category['title'] || category['name']),
        display_type: category['type']
      )

      mailchimp_category.save!
    end

    # Destroy any Effective::MailchimpGroups resources if they no longer returned by groups
    mailchimp_categories.each do |mailchimp_category|
      category = categories.find { |category| category['id'] == mailchimp_category.mailchimp_id }
      mailchimp_category.destroy! unless category.present?
    end
  end

  true
end

Instance Method Details

#to_sObject



69
70
71
# File 'app/models/effective/mailchimp_category.rb', line 69

def to_s
  name.presence || model_name.human
end