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
# 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"
    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



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

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



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

def campaigns()
    Campaigns.new self
end

#cast_error(body) ⇒ Object



53
54
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
# File 'lib/mailchimp.rb', line 53

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



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

def conversations()
    Conversations.new self
end

#ecommObject



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

def ecomm()
    Ecomm.new self
end

#foldersObject



166
167
168
# File 'lib/mailchimp.rb', line 166

def folders()
    Folders.new self
end


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

def gallery()
    Gallery.new self
end

#goalObject



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

def goal()
    Goal.new self
end

#helperObject



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

def helper()
    Helper.new self
end

#listsObject



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

def lists()
    Lists.new self
end

#mobileObject



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

def mobile()
    Mobile.new self
end

#neapolitanObject



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

def neapolitan()
    Neapolitan.new self
end

#read_configsObject



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

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



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

def reports()
    Reports.new self
end

#templatesObject



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

def templates()
    Templates.new self
end

#usersObject



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

def users()
    Users.new self
end

#vipObject



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

def vip()
    Vip.new self
end