Skip to content

Instantly share code, notes, and snippets.

@bigfleet
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigfleet/780eea5812164016e40b to your computer and use it in GitHub Desktop.
Save bigfleet/780eea5812164016e40b to your computer and use it in GitHub Desktop.
Gemfile
# Add literally these into env.example, to help newbies that follow you on this app.
# Put the real values into .env
MAILCHIMP_API_KEY=key
MAILCHIMP_LIST_NAME="List name"
# This is the model I needed to add to the list, add this in there somewhere.
after_save :subscribe_to_mailchimp
def subscribe_to_mailchimp
MailchimpInterface.subscribe(
MailchimpInterface.list_named(
MailchimpInterface::LIST_NAME), self)
end
# # In spec/models/candidate_spec.rb
# This represents the "mock" version of how to test.
# I think it's complicated and hard to read afterwards, but opinions can vary.
# It definitely does require less overall setup.
context "new candidates", focused: true do
it "should subscribe a new candidate to Mailchimp" do
expect {
l = double("list")
allow(l).to receive(:[]).with("name"){ MailchimpInterface::LIST_NAME }
allow(MailchimpInterface).to receive(:all_lists){ [l] }
expect(MailchimpInterface).to receive(:subscribe)
create(:candidate)
}.to change(Candidate, :count).by(1)
end
end
# Insert this into to your Gemfile
gem 'gibbon'
# Mailchimp interface, should be in app/interfaces/mailchimp_interface.rb
class MailchimpInterface
LIST_NAME = ENV["MAILCHIMP_LIST_NAME"]
def self.all_lists
client.lists.list["data"]
end
def self.list_named(name)
all_lists.select{ |l| l["name"] == name}.first
end
def self.members(list)
client.lists.members(id: list["id"])["data"]
end
# Note that this method has particular requirements
# of your model layer in terms of field names, etc.
def self.subscribe(list, user)
client.lists.subscribe({:id => list["id"],
:email => {:email => user.email},
:merge_vars => {:FNAME => user.first_name, :LNAME => user.last_name},
:double_optin => false})
end
def self.client
Gibbon::API.new
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment