Created
November 9, 2010 09:57
-
-
Save paveltyk/668919 to your computer and use it in GitHub Desktop.
Mail Chimp Test Task
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Mail Chimp Test Task | |
API_KEY = 'api-key' | |
LIST_NAME = 'list name' | |
require 'rubygems' | |
require 'xmlrpc/client' | |
require 'active_record' | |
# === Database Setup | |
ActiveRecord::Base.logger = Logger.new STDERR | |
ActiveRecord::Base.establish_connection :adapter => "sqlite3", :database => ":memory:" | |
ActiveRecord::Schema.define do | |
create_table :users do |t| | |
t.string :fname | |
t.string :lname | |
t.string :email | |
end | |
end | |
class User < ActiveRecord::Base | |
def to_mailchimp_member | |
MailChimp::Member.new email, {'FNAME' => fname, 'LNAME' => lname} | |
end | |
end | |
10.times { |i| User.create :email => "email-#{i}@email.com", :fname => "Name #{i}", :lname => "Surname #{i}" } | |
# === Mail Chimp Classes definition | |
module MailChimp | |
class Base | |
API_VERSION = '1.2' | |
cattr_accessor :api_client | |
end | |
class ApiClient | |
attr_reader :api_key | |
def initialize(api_key) | |
@api_key = api_key | |
@api_client = XMLRPC::Client.new_from_uri "http://#{dc}.api.mailchimp.com/#{Base::API_VERSION}/" | |
end | |
def dc | |
api_key.split('-').last | |
end | |
def call(method, *args) | |
@api_client.call(method, @api_key, *args) | |
end | |
end | |
class List | |
def self.all | |
Base.api_client.call("lists").map { |list_options| List.new list_options } | |
end | |
def initialize options = {} | |
@options = options.symbolize_keys | |
end | |
def id | |
@options[:id] | |
end | |
def <<(member) | |
Base.api_client.call "listSubscribe", id, member.email, member.merge_vars | |
end | |
def method_missing(method_name, *args) | |
if @options.has_key? method_name | |
return @options[method_name] | |
else | |
super | |
end | |
end | |
end | |
class Member | |
attr_accessor :email, :merge_vars | |
def initialize(email, merge_vars = {}) | |
@email = email | |
@merge_vars = merge_vars | |
end | |
end | |
end | |
# === Loading emails to Mail Chimp list | |
MailChimp::Base.api_client = MailChimp::ApiClient.new(API_KEY) | |
list = MailChimp::List.all.find { |l| l.name == LIST_NAME } | |
User.all.each do |user| | |
if list << user.to_mailchimp_member | |
puts "Successfully added #{user.email} to \"#{LIST_NAME}\" list" | |
else | |
puts "Failed to add #{user.email} to \"#{LIST_NAME}\" list" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment