Module: Mailjet::Resource

Included in:
Aggregategraphstatistics, Apikey, Apikeyaccess, Apikeytotals, Apitoken, Axtesting, Batchjob, Bouncestatistics, Campaign, Campaignaggregate, Campaigndraft, Campaigndraft_detailcontent, Campaigndraft_schedule, Campaigndraft_send, Campaigndraft_status, Campaigndraft_test, Campaigngraphstatistics, Campaignoverview, Campaignstatistics, Clickstatistics, Contact, ContactPii, Contact_getcontactslists, Contact_managecontactslists, Contact_managemanycontacts, Contactdata, Contactfilter, Contacthistorydata, Contactmetadata, Contactslist, ContactslistCsv, Contactslist_managecontact, Contactslist_managemanycontacts, Contactslistsignup, Contactstatistics, Csvimport, DNS, DNS_check, Domainstatistics, Eventcallbackurl, Geostatistics, Graphstatistics, Listrecipient, Listrecipientstatistics, Liststatistics, Manycontacts, Message, MessageDelivery, Messagehistory, Messageinformation, Messagesentstatistics, Messagestate, Messagestatistics, Metadata, Metasender, Myprofile, Newsletter, Newsletter_detailcontent, Newsletter_schedule, Newsletter_send, Newsletter_status, Newsletter_test, Newsletterblock, Newsletterproperties, Newslettertemplate, Newslettertemplateblock, Newslettertemplatecategory, Newslettertemplateproperties, Openinformation, Openstatistics, Parseroute, Preferences, RetrieveErrosCsv, Send, Sender, Sender_validate, Senderstatistics, Statcounters, Statistics_linkclick, Template, Template_detailcontent, Toplinkclicked, Trigger, User, Useragentstatistics, Widget, Widgetcustomvalue
Defined in:
lib/mailjet/resource.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

OPTIONS =

define here available options for filtering

[:version, :url, :perform_api_call, :api_key, :secret_key]
NON_JSON_URLS =

urls that don’t accept JSON input

['v3/send/message']
DATA_URLS =

url for send binary data , ‘CSVError/text:csv’

['plain', 'csv']

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_symbol, *arguments) ⇒ Object (private)

:nodoc:



376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/mailjet/resource.rb', line 376

def method_missing(method_symbol, *arguments) #:nodoc:
  method_name = method_symbol.to_s
  if method_name.end_with?("=")
    attributes[method_name.chop] = arguments.first
    return
  end

  if attributes.include?(method_name)
    return attributes[method_name]
  end

  super
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



264
265
266
# File 'lib/mailjet/resource.rb', line 264

def attributes
  @attributes
end

#persistedObject

Returns the value of attribute persisted.



264
265
266
# File 'lib/mailjet/resource.rb', line 264

def persisted
  @persisted
end

Class Method Details

.included(base) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mailjet/resource.rb', line 24

def self.included(base)
  base.extend ClassMethods
  base.class_eval do
    cattr_accessor :resource_path, :public_operations, :read_only, :filters, :resourceprop, :read_only_attributes, :action, :non_json_urls, :version
    cattr_writer :connection

    self.read_only_attributes = []

    def self.connection(options = {})
      class_variable_get(:@@connection) || default_connection(options)
    end

    def self.default_connection(options = {})
      Mailjet::Connection.new(
        "#{options[:url]}/#{options[:version]}/#{resource_path}",
        options[:api_key] || Mailjet.config.api_key,
        options[:secret_key] || Mailjet.config.secret_key,
        public_operations: public_operations,
        read_only: read_only,
        perform_api_call: options[:perform_api_call])
    end

    def self.default_headers
      if NON_JSON_URLS.include?(self.resource_path) # don't use JSON if Send API
        default_headers = { 'Accept' =>'application/json', 'Accept-Encoding' => 'deflate' }
      elsif DATA_URLS.any? do |data_type|
        default_headers = { 'Content-Type' => "text/#{data_type}" } if self.resource_path.include?(data_type)
        end
      else
        # use JSON if *not* Send API
        default_headers = {'Content-Type' =>'application/json', 'Accept' =>'application/json', 'Accept-Encoding' => 'deflate'}
      end
      return default_headers.merge!('User-Agent' => "mailjet-api-v3-ruby/#{Gem.loaded_specs["mailjet"].version}")
    end
  end
end

Instance Method Details

#deleteObject



330
331
332
# File 'lib/mailjet/resource.rb', line 330

def delete
  self.class.delete(id)
end

#initialize(_attributes = nil) ⇒ Object



266
267
268
# File 'lib/mailjet/resource.rb', line 266

def initialize(_attributes = nil)
  @attributes = ActiveSupport::HashWithIndifferentAccess.new(_attributes.reverse_merge(persisted: false))
end

#persisted?Boolean

Returns:

  • (Boolean)


270
271
272
# File 'lib/mailjet/resource.rb', line 270

def persisted?
  attributes[:persisted]
end

#save(options = {}) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/mailjet/resource.rb', line 274

def save(options = {})
  opts = self.class.define_options(options)

  if persisted?
    # case where the entity is updated
    response = connection(opts)[attributes[:id]].put(formatted_payload, default_headers)
  else
    # case where the entity is created
    response = connection(opts).post(formatted_payload, default_headers)
  end

  if opts[:perform_api_call] && !persisted?
    # get attributes only for entity creation
    self.attributes = if self.resource_path == 'send'
      response.respond_to?(:body) ? Yajl::Parser.parse(response.body) : Yajl::Parser.parse(response)
    else
      parse_api_json(response.body).first
    end
  end

  return true

rescue Mailjet::ApiError => e
  if e.code.to_s == "304"
    return true # When you save a record twice it should not raise error
  else
    raise e
  end
end

#save!(options = {}) ⇒ Object



304
305
306
# File 'lib/mailjet/resource.rb', line 304

def save!(options = {})
  save(options) || raise(StandardError.new("Resource not persisted"))
end

#update_attributes(attribute_hash = {}, options = {}) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/mailjet/resource.rb', line 314

def update_attributes(attribute_hash = {}, options = {})
  self.attributes.deep_merge!(attribute_hash) do |key, old, new|
    if old.is_a?(Array) && new.is_a?(Array)
      # uniqueness of hashes based on their value of "Name"
      (new + old).uniq do |data|
        data["Name"]
      end
    else
      new
    end
  end

  opts = self.class.define_options(options)
  save(opts)
end