Method: CouchClient::Document#save

Defined in:
lib/couch-client/document.rb

#saveObject

Tries to save the document to the server. If it us unable to, it will save the error and make it available via #error.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/couch-client/document.rb', line 53

def save
  # Ensure that "_id" is a String if it is defined.
  if self.key?("_id") && !self["_id"].is_a?(String)
    raise InvalidId.new("document _id must be a String")
  end
  
  # Documents without an id must use post, with an id must use put
  @code, body = if self.id
    @connection.hookup.put([self.id], nil, self)
  else
    @connection.hookup.post(nil, nil, self)
  end
  
  # If the document was saved
  if body["ok"]
    # Update id and rev, ensure the deleted flag is set to `false` and return `true`
    self.id ||= body["id"]
    self.rev  = body["rev"]
    @deleted  = false
    true
  else
    # Else save error message and return `false`.
    @error = {body["error"] => body["reason"]}
    false
  end
end