Class: Mautic::Model
- Inherits:
-
OpenStruct
- Object
- OpenStruct
- Mautic::Model
- Defined in:
- lib/mautic/model.rb
Defined Under Namespace
Classes: MauticHash
Class Method Summary collapse
Instance Method Summary collapse
- #attributes ⇒ Object
- #attributes=(hash) ⇒ Object
- #changes ⇒ Object
- #create ⇒ Object
- #destroy ⇒ Object
-
#initialize(connection, hash = nil) ⇒ Model
constructor
A new instance of Model.
- #save(force = false) ⇒ Object
- #update(force = false) ⇒ Object
Constructor Details
#initialize(connection, hash = nil) ⇒ Model
Returns a new instance of Model.
30 31 32 33 34 35 36 |
# File 'lib/mautic/model.rb', line 30 def initialize(connection, hash=nil) @connection = connection @table = MauticHash.new self.attributes = { created_at: hash['dateAdded']&.to_time, updated_at: hash['dateModified']&.to_time } if hash assign_attributes(hash) clear_changes end |
Class Method Details
.endpoint ⇒ Object
20 21 22 |
# File 'lib/mautic/model.rb', line 20 def endpoint name.demodulize.underscore.pluralize end |
Instance Method Details
#attributes ⇒ Object
81 82 83 |
# File 'lib/mautic/model.rb', line 81 def attributes @table.to_h end |
#attributes=(hash) ⇒ Object
85 86 87 88 89 90 |
# File 'lib/mautic/model.rb', line 85 def attributes=(hash) hash.each_pair do |k, v| k = k.to_sym @table[k] = v end end |
#changes ⇒ Object
77 78 79 |
# File 'lib/mautic/model.rb', line 77 def changes @table.changes end |
#create ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/mautic/model.rb', line 55 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 |
#destroy ⇒ Object
67 68 69 70 71 72 73 74 75 |
# File 'lib/mautic/model.rb', line 67 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
38 39 40 |
# File 'lib/mautic/model.rb', line 38 def save(force = false) id.present? ? update(force) : create end |
#update(force = false) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/mautic/model.rb', line 42 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 |