Ruby Gem and Rails Plugin for Mailchimp
Recently, the limitations of the acts_as_mailchimp plugin that I threw together a while back have been staring me in the face. The more that I work with Mailchimp, and the more that they improve their API, the more I realized that it was time to do something about it.
UPDATE: We are no longer maintaining the Acts_As_Mailchimp plugin. Instead, we recommend using the Hominid gem, which has just been updated to version 2.0.2, making most of this post irrelevant.
The Hominid Gem
Hominid is a gem that wraps the Mailchimp API so that you can easily work with it in Ruby or Rails. You can install Hominid as a plugin by typing:
script/plugin install git://github.com/bgetting/hominid.git
Or, you can install it as a gem by including the following in your environment.rb file:
config.gem "bgetting-hominid", :lib => 'hominid', :source => "http://gems.github.com"
If you use Hominid as a gem, be sure to create a YAML file at config/hominid.yml to hold your Mailchimp login information for each environment. From there usage is pretty simple. For example, to add someone to a mailing list you might use:
h = Hominid.new
list = h.lists.find {|list| list["name"] == "My Mailing List" }
h.subscribe(list["id"], 'bob@smith.com')
We first create a new Hominid object, which will log in to Mailchimp using your account information from the hominid.yml file. From there, we use the lists method to return all the mailing lists at Mailchimp for this account, and pull out the one with the name that we are looking for. We use that list’s id to subscribe someone to the list. Pretty simple.
There are also methods for dealing with campaigns and other things. One particular method that is worth noting is the convert_css_to_inline method, which uses the Mailchimp API to convert any CSS declarations in an HTML document into inline styles for use in emails. That thing comes in handy!
I haven’t yet had time to write tests for this gem. I would love any input that anyone has with regard to the best way to test this, and how to write the tests. Hopefully the lack of adequate tests doesn’t wreck anyone’s day.
Acts_As_Mailchimp Plugin
The Acts_As_Maichimp plugin then needed to be updated. I decided that since Hominid wraps nearly all the functionality of the plugin, I would just make it dependent on Hominid. So one you have Hominid installed, you can install acts_as_mailchimp by typing:
script/plugin install git://github.com/bgetting/acts_as_mailchimp.git
Now add the following to your model so that you can add, remove and update a member of a Mailchimp mailing list:
acts_as_mailchimp
For the most part, the plugin now just wraps the process of finding the list ID of the list you want to work with, and the connecting to Mailchimp using Hominid.
Someone also pointed out the lack of tests on this plugin. Again, I apologize for not taking the time, and would welcome any suggestions for what would make effective tests for such a plugin.