Class: Effective::MailchimpInterest

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

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

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



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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'app/models/effective/mailchimp_interest.rb', line 38

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

  mailchimp_lists.each do |mailchimp_list|
    mailchimp_list.mailchimp_categories.each do |mailchimp_category|

      # All the Interests from Mailchimp
      interests = api.interests(mailchimp_list.mailchimp_id, mailchimp_category.mailchimp_id)

      # Get all our existing Effective::MailchimpGroup records
      mailchimp_interests = where(mailchimp_list: mailchimp_list, mailchimp_category: mailchimp_category)

      # Find or create Effective::MailchimpInterests based on existing lists and categories 
      interests.each do |interest|
        mailchimp_id = interest['id']
        mailchimp_interest = mailchimp_interests.find { |mi| mi.mailchimp_id == mailchimp_id } || new()

        mailchimp_interest.assign_attributes(
          mailchimp_list: mailchimp_list,
          mailchimp_category: mailchimp_category,

          mailchimp_id: mailchimp_id,

          list_id: interest['list_id'],
          list_name: mailchimp_list.name,

          category_id: interest['category_id'],
          category_name: mailchimp_category.name,

          name: interest['name'],
          display_order: interest['display_order'],
          subscriber_count: interest['subscriber_count']
        )

        mailchimp_interest.assign_attributes(can_subscribe: true) if mailchimp_interest.new_record?
        mailchimp_interest.save!
      end

      # Destroy any Effective::MailchimpGroups resources if they no longer returned by interests
      mailchimp_interests.each do |mailchimp_interest|
        interest = interests.find { |interest| interest['id'] == mailchimp_interest.mailchimp_id }
        mailchimp_interest.destroy! unless interest.present?
      end
    end
  end

  true
end

Instance Method Details

#to_sObject



88
89
90
# File 'app/models/effective/mailchimp_interest.rb', line 88

def to_s
  name.presence || model_name.human
end