Class: Mautic::Model

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/mautic/model.rb

Direct Known Subclasses

Contact, Form

Defined Under Namespace

Classes: Attribute, MauticHash

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, hash = nil) ⇒ Model

Returns a new instance of Model.



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

def initialize(connection, hash=nil)
  @connection = connection
  @table = MauticHash.new
  self.attributes = { id: hash['id'], created_at: hash['dateAdded']&.to_time, updated_at: hash['dateModified']&.to_time } if hash
  assign_attributes(hash)
  clear_changes
end

Class Method Details

.endpointObject



28
29
30
# File 'lib/mautic/model.rb', line 28

def endpoint
  name.demodulize.underscore.pluralize
end

.in(connection) ⇒ Object



32
33
34
# File 'lib/mautic/model.rb', line 32

def in(connection)
  Proxy.new(connection, endpoint)
end

Instance Method Details

#attributesObject



89
90
91
# File 'lib/mautic/model.rb', line 89

def attributes
  @table.to_h
end

#attributes=(hash) ⇒ Object



93
94
95
96
97
98
# File 'lib/mautic/model.rb', line 93

def attributes=(hash)
  hash.each_pair do |k, v|
    k = k.to_sym
    @table[k] = v
  end
end

#changesObject



85
86
87
# File 'lib/mautic/model.rb', line 85

def changes
  @table.changes
end

#createObject



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mautic/model.rb', line 63

def create
  begin
    json = @connection.request(:post, "api/#{endpoint}/#{id}/new", { body: to_h })
    self.attributes = json[endpoint.singularize]
    clear_changes
  rescue ValidationError => e
    self.errors = e.errors
  end

  self.errors.blank?
end

#destroyObject



75
76
77
78
79
80
81
82
83
# File 'lib/mautic/model.rb', line 75

def destroy
  begin
    @connection.request(:delete, "api/#{endpoint}/#{id}/delete")
    true
  rescue RequestError => e
    self.errors = e.errors
    false
  end
end

#save(force = false) ⇒ Object



46
47
48
# File 'lib/mautic/model.rb', line 46

def save(force = false)
  id.present? ? update(force) : create
end

#update(force = false) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mautic/model.rb', line 50

def update(force = false)
  return false if changes.blank?
  begin
    json = @connection.request((force && :put || :patch), "api/#{endpoint}/#{id}/edit", { body: to_h })
    self.attributes = json[endpoint.singularize]
    clear_changes
  rescue ValidationError => e
    self.errors = e.errors
  end

  self.errors.blank?
end