Class: Namely::Model

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

Instance Method Summary collapse

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.

Returns:

  • (Boolean)


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.

Returns:

  • (Model)

    the model itself, if saving succeeded.

Raises:



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.

Examples:

my_profile.update(
  middle_name: "Ludwig"
)

Parameters:

  • attributes (Hash)

    the attributes to be updated on the model.

Returns:

  • (Model)

    the updated model.

Raises:



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