5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MailChimpのsubscribe/unsubscribe

Last updated at Posted at 2013-09-27

tatemae-consultancy/hominidというgemを使ってサービスの設定状況とMailChimpのsubscribe/unsubscribeを連携する.

user.rb
class User < ActiveRecord::Base
  after_create do
    subscribe_mailchimp
  end

  after_update do
    if email.present? && email_was.present? && email != email_was
      begin
        mailchimp.list_update_member(mailchimp_list_id, email_was,
          { EMAIL: email}, 'html', false)
      rescue => e
        logger.error "Failed to update newsletter: #{url_name} #{e}"
      end
    end
    true
  end

  before_destroy do |user|
    unsubscribe_mailchimp
  end

  def subscribe_mailchimp
    return if email.blank?
    mailchimp.list_subscribe(mailchimp_list_id, email, {}, 'html',
      false, true, false, false)
  rescue => e
    logger.error "Failed to subscribe newsletter: #{url_name} #{e}"
  end

  def unsubscribe_mailchimp
    return if email.blank?
    mailchimp.list_unsubscribe(mailchimp_list_id, email, false, false, false)
  rescue => e
    logger.error "Failed to unsubscribe newsletter: #{url_name} #{e}"
  end

  def mailchimp
    Hominid::API.new(APP_CONFIG['mailchimp']['api_key']) # Do not cache.
  end

  def mailchimp_list_id
    APP_CONFIG['mailchimp']['list_id']
  end
end
5
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?