by
back

Integrate mailchimp in ruby on rails with a resque worker

Mailchimp is a cool webapplication for sending newsletters. They have a powerful api for all of their features.

If you want to integrate mailchimp into your ruby on rails application, you can use the gem gibbon

Gibbon is an API wrapper for the MailChimp API.

First you need to add gibbon to your Gemfile

Gemfile

gem 'gibbon'

Next create an initializer

config/initializers/gibbon.rb

Gibbon::API.throws_exceptions = false
$mailchimp = Gibbon::API.new('YOUR-MAILCHIMP-API-TOKEN')

You find the neccessary API key on your Mailchimp Account Page

Now, after a quick "bundle install" and a restart of your webserver, you can communicate with mailchimp over $mailchimp.

To subscribe or unsubscribe a user to one of your mailchimp lists, you can use the following-code

app/models/user.rb

def subscribe_to_mailchimp(optin = false)
    response = $mailchimp.lists.subscribe({
       id: 'YOUR-LIST-ID',
       email: {email: self.email},
       merge_vars: { fname: self.name1, lname: self.name2 },
       double_optin: optin,
    })
end

def unsubscribe_from_mailchimp(notify = false)
    response = $mailchimp.lists.unsubscribe({
       id: 'YOUR-LIST-ID',
       email: {email: self.email},
       :delete_member => false, 
       :send_notify => notify
    })
end

You find the List ID on the "List name & defaults" page of your Mailchimp List.

Now you can subscribe a user in a controller via

app/controllers/users_controller.rb

def subscribe
  @user = User.find(params[:id])
  @user.subscribe_to_mailchimp(true)
  # redirect to some other url
end

The API call might take some seconds and to avoid the delay you should move that part to a worker process.
The code for a resque worker would be

app/workers/mailchimp_subscriber.rb

class MailchimpSubscriber
    @queue = :mailchimp_api
    def self.perform(user_id)
        User.find(user_id).subscribe_to_mailchimp
    end
end

Now you can subscribe the user without delay and even in an after_create callback in the model:

app/models/user.rb

class User < ActiveRecord::Base
    after_create :subscribe_to_list

    private
    def subscribe_to_list
        Resque.enqueue(MailchimpSubscriber, self.id)
    end
end


comments powered by Disqus