Module: Mailjet::Resource::ClassMethods

Defined in:
lib/mailjet/resource.rb

Instance Method Summary collapse

Instance Method Details

#all(params = {}, options = {}) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/mailjet/resource.rb', line 68

def all(params = {}, options = {})
  opts = define_options(options)
  params = format_params(params)
  response = connection(opts).get(default_headers.merge!(params: params))
  attribute_array = parse_api_json(response.body)
  attribute_array.map{ |attributes| instanciate_from_api(attributes) }
rescue Mailjet::ApiError => error
  raise error
end

#camelcase_keys(hash) ⇒ Object



226
227
228
# File 'lib/mailjet/resource.rb', line 226

def camelcase_keys(hash)
  map_keys(hash, :camelcase)
end

#convert_dates_from(data) ⇒ Object

Method – taken from the ActiveSupport library – which converts the date-time from “2014-05-19T15:31:09Z” to “Mon, 19 May 2014 15:31:09 +0000” format. We may have to change this in the future if ActiveSupport’s JSON implementation changes



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/mailjet/resource.rb', line 193

def convert_dates_from(data)
  case data
  when nil
    nil
  when /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
    begin
      DateTime.iso8601(data)
    rescue ArgumentError
      data
    end
  when Array
    data.map! { |d| convert_dates_from(d) }
  when Hash
    data.each do |key, value|
      data[key] = convert_dates_from(value)
    end
  else
    data
  end
end

#count(options = {}) ⇒ Object



78
79
80
81
82
83
84
85
# File 'lib/mailjet/resource.rb', line 78

def count(options = {})
  opts = define_options(options)
  response_json = connection(opts).get(default_headers.merge!(params: {limit: 1, countrecords: 1}))
  response_hash = Yajl::Parser.parse(response_json.body)
  response_hash['Total']
rescue Mailjet::ApiError => error
  raise error
end

#create(attributes = {}, options = {}) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/mailjet/resource.rb', line 117

def create(attributes = {}, options = {})
  # if action method, ammend url to appropriate id
  opts = define_options(options)
  self.resource_path = create_action_resource_path(attributes[:id]) if (self.action and attributes[:id])
  attributes.tap { |hs| hs.delete(:id) }

  if Mailjet.config.default_from and self.resource_path == 'send/'
    address = Mail::AddressList.new(Mailjet.config.default_from).addresses[0]
    default_attributes = { :from_email => address.address, :from_name => address.display_name}
  else
    default_attributes = {}
  end

  attributes = default_attributes.merge(attributes)

  self.new(attributes).tap do |resource|
    resource.save!(opts)
    resource.attributes[:persisted] = true
  end
end

#create_action_resource_path(id, job_id = nil) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/mailjet/resource.rb', line 175

def create_action_resource_path(id, job_id = nil)
  url_elements = self.resource_path.split("/")
  url_elements.delete_at(url_elements.length-1) if url_elements.last.to_i > 0 #if there is a trailing number for the job id from last call, delete it

  if !(url_elements[1] == "contacts" && self.action == "managemanycontacts")
    url_elements[2] = id.to_s
  end

  url_elements << job_id.to_s if job_id #if job_id exists, amend it to end of the URI
  url = url_elements.join("/")

  return url
end

#define_options(options = {}) ⇒ Object



252
253
254
255
256
257
258
259
260
# File 'lib/mailjet/resource.rb', line 252

def define_options(options = {})
  # merge default options with given ones on-the-fly
  {
    version: version || Mailjet.config.api_version,
    url: Mailjet.config.end_point,
    perform_api_call: Mailjet.config.perform_api_call
  }
  .merge(options.symbolize_keys.slice(*OPTIONS))
end

#delete(id, options = {}) ⇒ Object



138
139
140
141
142
143
144
145
# File 'lib/mailjet/resource.rb', line 138

def delete(id, options = {})
   # if action method, ammend url to appropriate id
   opts = define_options(options)
   self.resource_path = create_action_resource_path(id) if self.action
   connection(opts)[id].delete(default_headers)
rescue Mailjet::ApiError => error
  raise error
end

#find(id, job_id = nil, options = {}) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/mailjet/resource.rb', line 87

def find(id, job_id = nil, options = {})
  normalized_id = if id.is_a? String
    URI.encode_www_form_component(id)
  else
    id
  end

  # if action method, ammend url to appropriate id
  opts = define_options(options)
  self.resource_path = create_action_resource_path(normalized_id, job_id) if self.action

  attributes = parse_api_json(connection(opts)[normalized_id].get(default_headers).body).first
  instanciate_from_api(attributes)

rescue Mailjet::CommunicationError => e
  if e.code == 404
    nil
  else
    raise e
  end
end

#find_by_id(id, options = {}) ⇒ Object



110
111
112
113
114
115
# File 'lib/mailjet/resource.rb', line 110

def find_by_id(id, options = {})
  # if action method, ammend url to appropriate id
  opts = define_options(options)
  self.resource_path = create_action_resource_path(id) if self.action
  connection(opts).get(default_headers)
end

#first(params = {}, options = {}) ⇒ Object



62
63
64
65
66
# File 'lib/mailjet/resource.rb', line 62

def first(params = {}, options = {})
  all(params.merge!(limit: 1), options).first
rescue Mailjet::ApiError => error
  raise error
end

#format_params(params) ⇒ Object



215
216
217
218
219
220
221
222
223
224
# File 'lib/mailjet/resource.rb', line 215

def format_params(params)
  if params[:sort]
    params[:sort] = params[:sort].map do |attribute, direction|
      attribute = attribute.to_s.camelcase
      direction = direction.to_s.upcase
      "#{attribute} #{direction}"
    end.join(', ')
  end
  camelcase_keys params
end

#instanciate_from_api(attributes = {}) ⇒ Object



156
157
158
# File 'lib/mailjet/resource.rb', line 156

def instanciate_from_api(attributes = {})
  self.new(attributes.merge!(persisted: true))
end

#map_keys(hash, method) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/mailjet/resource.rb', line 234

def map_keys(hash, method)
  hash.inject({}) do |_hash, (key, value)|
    # new_key = key.to_s.send(method)
    new_key =
      if key == "text_part"
        'Text-part'
      elsif key == "html_part"
        'Html-part'
      elsif key == "inline_attachments"
        'Inline_attachments'
      else
        key.to_s.send(method)
      end
    _hash[new_key] = value
    _hash
  end
end

#parse_api_json(response_json) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/mailjet/resource.rb', line 160

def parse_api_json(response_json)
  response_hash = Yajl::Parser.parse(response_json)

  #Take the response from the API and put it through a method -- taken from the ActiveSupport library -- which converts
  #the date-time from "2014-05-19T15:31:09Z" to "Mon, 19 May 2014 15:31:09 +0000" format.
  response_hash = convert_dates_from(response_hash)

  if response_hash['Data']
    response_data_array = response_hash['Data']
  else
    response_data_array = response_hash
  end
  response_data_array.map{ |response_data| underscore_keys(response_data) }
end

#send_data(id, binary_data = nil, options = {}) ⇒ Object



147
148
149
150
151
152
153
154
# File 'lib/mailjet/resource.rb', line 147

def send_data(id, binary_data = nil, options = {})
  opts = define_options(options)
  self.resource_path = create_action_resource_path(id) if self.action
  response = connection(opts).post(binary_data, default_headers.merge({'Content-Length' => "#{binary_data.size}", 'Transfer-Encoding' => 'chunked'}))

  response_hash = response.respond_to?(:body) ? Yajl::Parser.parse(response.body) : Yajl::Parser.parse(response)
  response_hash['ID'] ? response_hash['ID'] : response_hash
end

#underscore_keys(hash) ⇒ Object



230
231
232
# File 'lib/mailjet/resource.rb', line 230

def underscore_keys(hash)
  map_keys(hash, :underscore)
end