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
34
35
# File 'lib/mailchimp.rb', line 13

def initialize(apikey=nil, debug=false)
    @host = 'https://api.mailchimp.com'
    @path = '/2.0/'
    @dc = 'us1'
    @apikey = apikey
    if @apikey.split('-').length == 2                
        @host = "https://#{@apikey.split('-')[1]}.api.mailchimp.com"
    end

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

    if not apikey
        if ENV['MAILCHIMP_APIKEY']
            apikey = ENV['MAILCHIMP_APIKEY']
        else
            apikey = read_configs
        end
    end

    raise Error, 'You must provide a MailChimp API key' if not apikey
    @apikey = apikey
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



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

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



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

def campaigns()
    Campaigns.new self
end

#cast_error(body) ⇒ Object



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

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
    }

    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

#ecommObject



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

def ecomm()
    Ecomm.new self
end

#foldersObject



164
165
166
# File 'lib/mailchimp.rb', line 164

def folders()
    Folders.new self
end


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

def gallery()
    Gallery.new self
end

#helperObject



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

def helper()
    Helper.new self
end

#listsObject



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

def lists()
    Lists.new self
end

#mobileObject



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

def mobile()
    Mobile.new self
end

#neapolitanObject



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

def neapolitan()
    Neapolitan.new self
end

#read_configsObject



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

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



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

def reports()
    Reports.new self
end

#templatesObject



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

def templates()
    Templates.new self
end

#usersObject



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

def users()
    Users.new self
end

#vipObject



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

def vip()
    Vip.new self
end