Class: Mailchimp::API

Inherits:
Object
  • Object
show all
Defined in:
lib/mailchimp.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(apikey = nil, debug = false) ⇒ API

Returns a new instance of API.

Raises:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mailchimp.rb', line 13

def initialize(apikey=nil, debug=false)
    @host = 'https://api.mailchimp.com'
    @path = '/2.0/'
    @dc = 'us1'

    unless apikey
        apikey = ENV['MAILCHIMP_APIKEY'] || read_configs
    end

    raise Error, 'You must provide a MailChimp API key' unless apikey

    @apikey = apikey
    if @apikey.split('-').length == 2
        @host = "https://#{@apikey.split('-')[1]}.api.mailchimp.com"
    else
        raise InvalidApiKeyError, 'Your MailChimp API key must contain a suffix subdomain (e.g. "-us8").'
    end

    @session = Excon.new @host
    @debug = debug
end

Instance Attribute Details

#apikeyObject

Returns the value of attribute apikey.



11
12
13
# File 'lib/mailchimp.rb', line 11

def apikey
  @apikey
end

#debugObject

Returns the value of attribute debug.



11
12
13
# File 'lib/mailchimp.rb', line 11

def debug
  @debug
end

#hostObject

Returns the value of attribute host.



11
12
13
# File 'lib/mailchimp.rb', line 11

def host
  @host
end

#pathObject

Returns the value of attribute path.



11
12
13
# File 'lib/mailchimp.rb', line 11

def path
  @path
end

#sessionObject

Returns the value of attribute session.



11
12
13
# File 'lib/mailchimp.rb', line 11

def session
  @session
end

Instance Method Details

#call(url, params = {}) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/mailchimp.rb', line 35

def call(url, params={})
    params[:apikey] = @apikey
    params = JSON.generate(params)
    r = @session.post(:path => "#{@path}#{url}.json", :headers => {'Content-Type' => 'application/json'}, :body => params)
    
    cast_error(r.body) if r.status != 200
    return JSON.parse(r.body)
end

#campaignsObject



195
196
197
# File 'lib/mailchimp.rb', line 195

def campaigns()
    Campaigns.new self
end

#cast_error(body) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/mailchimp.rb', line 55

def cast_error(body)

    error_map = {
        'ValidationError' => ValidationError,
        'ServerError_MethodUnknown' => ServerMethodUnknownError,
        'ServerError_InvalidParameters' => ServerInvalidParametersError,
        'Unknown_Exception' => UnknownExceptionError,
        'Request_TimedOut' => RequestTimedOutError,
        'Zend_Uri_Exception' => ZendUriExceptionError,
        'PDOException' => PDOExceptionError,
        'Avesta_Db_Exception' => AvestaDbExceptionError,
        'XML_RPC2_Exception' => XMLRPC2ExceptionError,
        'XML_RPC2_FaultException' => XMLRPC2FaultExceptionError,
        'Too_Many_Connections' => TooManyConnectionsError,
        'Parse_Exception' => ParseExceptionError,
        'User_Unknown' => UserUnknownError,
        'User_Disabled' => UserDisabledError,
        'User_DoesNotExist' => UserDoesNotExistError,
        'User_NotApproved' => UserNotApprovedError,
        'Invalid_ApiKey' => InvalidApiKeyError,
        'User_UnderMaintenance' => UserUnderMaintenanceError,
        'Invalid_AppKey' => InvalidAppKeyError,
        'Invalid_IP' => InvalidIPError,
        'User_DoesExist' => UserDoesExistError,
        'User_InvalidRole' => UserInvalidRoleError,
        'User_InvalidAction' => UserInvalidActionError,
        'User_MissingEmail' => UserMissingEmailError,
        'User_CannotSendCampaign' => UserCannotSendCampaignError,
        'User_MissingModuleOutbox' => UserMissingModuleOutboxError,
        'User_ModuleAlreadyPurchased' => UserModuleAlreadyPurchasedError,
        'User_ModuleNotPurchased' => UserModuleNotPurchasedError,
        'User_NotEnoughCredit' => UserNotEnoughCreditError,
        'MC_InvalidPayment' => MCInvalidPaymentError,
        'List_DoesNotExist' => ListDoesNotExistError,
        'List_InvalidInterestFieldType' => ListInvalidInterestFieldTypeError,
        'List_InvalidOption' => ListInvalidOptionError,
        'List_InvalidUnsubMember' => ListInvalidUnsubMemberError,
        'List_InvalidBounceMember' => ListInvalidBounceMemberError,
        'List_AlreadySubscribed' => ListAlreadySubscribedError,
        'List_NotSubscribed' => ListNotSubscribedError,
        'List_InvalidImport' => ListInvalidImportError,
        'MC_PastedList_Duplicate' => MCPastedListDuplicateError,
        'MC_PastedList_InvalidImport' => MCPastedListInvalidImportError,
        'Email_AlreadySubscribed' => EmailAlreadySubscribedError,
        'Email_AlreadyUnsubscribed' => EmailAlreadyUnsubscribedError,
        'Email_NotExists' => EmailNotExistsError,
        'Email_NotSubscribed' => EmailNotSubscribedError,
        'List_MergeFieldRequired' => ListMergeFieldRequiredError,
        'List_CannotRemoveEmailMerge' => ListCannotRemoveEmailMergeError,
        'List_Merge_InvalidMergeID' => ListMergeInvalidMergeIDError,
        'List_TooManyMergeFields' => ListTooManyMergeFieldsError,
        'List_InvalidMergeField' => ListInvalidMergeFieldError,
        'List_InvalidInterestGroup' => ListInvalidInterestGroupError,
        'List_TooManyInterestGroups' => ListTooManyInterestGroupsError,
        'Campaign_DoesNotExist' => CampaignDoesNotExistError,
        'Campaign_StatsNotAvailable' => CampaignStatsNotAvailableError,
        'Campaign_InvalidAbsplit' => CampaignInvalidAbsplitError,
        'Campaign_InvalidContent' => CampaignInvalidContentError,
        'Campaign_InvalidOption' => CampaignInvalidOptionError,
        'Campaign_InvalidStatus' => CampaignInvalidStatusError,
        'Campaign_NotSaved' => CampaignNotSavedError,
        'Campaign_InvalidSegment' => CampaignInvalidSegmentError,
        'Campaign_InvalidRss' => CampaignInvalidRssError,
        'Campaign_InvalidAuto' => CampaignInvalidAutoError,
        'MC_ContentImport_InvalidArchive' => MCContentImportInvalidArchiveError,
        'Campaign_BounceMissing' => CampaignBounceMissingError,
        'Campaign_InvalidTemplate' => CampaignInvalidTemplateError,
        'Invalid_EcommOrder' => InvalidEcommOrderError,
        'Absplit_UnknownError' => AbsplitUnknownError,
        'Absplit_UnknownSplitTest' => AbsplitUnknownSplitTestError,
        'Absplit_UnknownTestType' => AbsplitUnknownTestTypeError,
        'Absplit_UnknownWaitUnit' => AbsplitUnknownWaitUnitError,
        'Absplit_UnknownWinnerType' => AbsplitUnknownWinnerTypeError,
        'Absplit_WinnerNotSelected' => AbsplitWinnerNotSelectedError,
        'Invalid_Analytics' => InvalidAnalyticsError,
        'Invalid_DateTime' => InvalidDateTimeError,
        'Invalid_Email' => InvalidEmailError,
        'Invalid_SendType' => InvalidSendTypeError,
        'Invalid_Template' => InvalidTemplateError,
        'Invalid_TrackingOptions' => InvalidTrackingOptionsError,
        'Invalid_Options' => InvalidOptionsError,
        'Invalid_Folder' => InvalidFolderError,
        'Invalid_URL' => InvalidURLError,
        'Module_Unknown' => ModuleUnknownError,
        'MonthlyPlan_Unknown' => MonthlyPlanUnknownError,
        'Order_TypeUnknown' => OrderTypeUnknownError,
        'Invalid_PagingLimit' => InvalidPagingLimitError,
        'Invalid_PagingStart' => InvalidPagingStartError,
        'Max_Size_Reached' => MaxSizeReachedError,
        'MC_SearchException' => MCSearchExceptionError,
        'Goal_SaveFailed' => GoalSaveFailedError,
        'Conversation_DoesNotExist' => ConversationDoesNotExistError,
        'Conversation_ReplySaveFailed' => ConversationReplySaveFailedError,
        'File_Not_Found_Exception' => FileNotFoundExceptionError,
        'Folder_Not_Found_Exception' => FolderNotFoundExceptionError,
        'Folder_Exists_Exception' => FolderExistsExceptionError
    }

    begin
        error_info = JSON.parse(body)
        if error_info['status'] != 'error' or not error_info['name']
            raise Error, "We received an unexpected error: #{body}"
        end
        if error_map[error_info['name']]
            raise error_map[error_info['name']], error_info['error']
        else
            raise Error, error_info['error']
        end
    rescue JSON::ParserError
        raise Error, "We received an unexpected error: #{body}"
    end
end

#conversationsObject



183
184
185
# File 'lib/mailchimp.rb', line 183

def conversations()
    Conversations.new self
end

#ecommObject



186
187
188
# File 'lib/mailchimp.rb', line 186

def ecomm()
    Ecomm.new self
end

#foldersObject



168
169
170
# File 'lib/mailchimp.rb', line 168

def folders()
    Folders.new self
end


204
205
206
# File 'lib/mailchimp.rb', line 204

def gallery()
    Gallery.new self
end

#goalObject



207
208
209
# File 'lib/mailchimp.rb', line 207

def goal()
    Goal.new self
end

#helperObject



177
178
179
# File 'lib/mailchimp.rb', line 177

def helper()
    Helper.new self
end

#listsObject



192
193
194
# File 'lib/mailchimp.rb', line 192

def lists()
    Lists.new self
end

#mobileObject



180
181
182
# File 'lib/mailchimp.rb', line 180

def mobile()
    Mobile.new self
end

#neapolitanObject



189
190
191
# File 'lib/mailchimp.rb', line 189

def neapolitan()
    Neapolitan.new self
end

#read_configsObject



44
45
46
47
48
49
50
51
52
53
# File 'lib/mailchimp.rb', line 44

def read_configs()
    [File.expand_path('~/.mailchimp.key'), '/etc/mailchimp.key'].delete_if{ |p| not File.exist? p}.each do |path|
        f = File.new path
        apikey = f.read.strip
        f.close
        return apikey if apikey != ''
    end

    return nil
end

#reportsObject



201
202
203
# File 'lib/mailchimp.rb', line 201

def reports()
    Reports.new self
end

#templatesObject



171
172
173
# File 'lib/mailchimp.rb', line 171

def templates()
    Templates.new self
end

#usersObject



174
175
176
# File 'lib/mailchimp.rb', line 174

def users()
    Users.new self
end

#vipObject



198
199
200
# File 'lib/mailchimp.rb', line 198

def vip()
    Vip.new self
end