Class: Namely::Model
- Inherits:
-
OpenStruct
- Object
- OpenStruct
- Namely::Model
- Defined in:
- lib/namely/model.rb
Instance Method Summary collapse
-
#initialize(resource_gateway, attributes) ⇒ Model
constructor
A new instance of Model.
-
#persisted? ⇒ Boolean
Return true if the model exists (in some state) on the server.
-
#save! ⇒ Model
Try to persist the current object to the server by creating a new resource or updating an existing one.
-
#update(attributes) ⇒ Model
Update the attributes of this model.
Constructor Details
#initialize(resource_gateway, attributes) ⇒ Model
Returns a new instance of Model.
5 6 7 8 |
# File 'lib/namely/model.rb', line 5 def initialize(resource_gateway, attributes) @resource_gateway = resource_gateway super(attributes) end |
Instance Method Details
#persisted? ⇒ Boolean
Return true if the model exists (in some state) on the server.
58 59 60 |
# File 'lib/namely/model.rb', line 58 def persisted? id != nil end |
#save! ⇒ Model
Try to persist the current object to the server by creating a new resource or updating an existing one. Raise an error if the object can’t be saved.
17 18 19 20 21 22 23 24 25 26 |
# File 'lib/namely/model.rb', line 17 def save! if persisted? update(to_h) else self.id = resource_gateway.create(to_h) end self rescue RestClient::Exception => e raise_failed_request_error(e) end |
#update(attributes) ⇒ Model
Update the attributes of this model. Assign the attributes according to the hash, then persist those changes on the server.
41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/namely/model.rb', line 41 def update(attributes) attributes.each do |key, value| self[key] = value end begin resource_gateway.update(id, attributes) rescue RestClient::Exception => e raise_failed_request_error(e) end self end |