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