It's the weekend, so obviously it's time to roll up my sleeves and get some serious work done. Last night, I felt that it was time that I put some effort into building a newsletter group, at least starting via my blog.
I want this to be reusable too — and having looked at the most popular Mailchimp library's latest efforts in upgrading to Mailchimp's API v3.0, I just said 'screw it' — I'm going to build it from scratch.
My favourite libcurl
Ruby wrapper is Curb, so this is used within my API's base. This simple DSL isn't ready for public prime time consumption, but it'll give you a rough idea of the approach I've taken
module Mailchimp
class Member < Api::Base
def initialize(list)
super()
# FIXME: Check that `list` is an instance of `Mailchimp::List`
@list_id = list.id
@resource_url = "/lists/#{@list_id}/members"
end
attr_reader :resource_url
attr_accessor :id, :email_address, :email_type, :status, :last_changed
# Fetches this member's `List`
#
# @example DSL example
# list = Mailchimp::List.new.fetch('LIST_ID_GOES_HERE')
# member = Mailchimp::Member.new(list)
# member.list
# @return [List] the list object
def list
List.new.fetch(@list_id)
end
def all
l = []
status, response = get_json(resource_url)
if response && status && status == :success && response["members"].any?
response["members"].each do |member|
l << decorate_with(member)
end
elsif status != :success
Rails.logger.tagged('Mailchimp::Member#all') { Rails.logger.debug "ERROR: #{response}" }
return false
end
l
end
# @example DSL example
# member = Mailchimp::Member.new Mailchimp::List.new.fetch('LIST_ID_GOES_HERE')
# member.email_address = "foo@bar.com"
# member.create
def create
member = {
status: "subscribed",
email_address: self.email_address
}
status, response = post_json(resource_url, member.to_json)
if response && status && status == :success
return decorate_with(response)
elsif status != :success
Rails.logger.tagged('Mailchimp::Member#create') { Rails.logger.debug "ERROR: #{response}" }
false
end
end
def delete(id)
delete_json("#{resource_url}/#{id}/") if id.present?
end
end
end
Let me know your thoughts in the comments, I'm off to wire this up now...