Method: Medea::JasonObject#persist_changes

Defined in:
lib/medea/jasonobject.rb

#persist_changes(method = :post) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/medea/jasonobject.rb', line 200

def persist_changes method = :post
  payload = self.serialise

  post_headers = {
      :content_type => 'application/json',
      "X-KEY"       => self.jason_key,
      "X-CLASS"     => self.class.name
      #also want to add the eTag here!
      #may also want to add any other indexable fields that the user specifies?
  }
  post_headers["IF-MATCH"] = @__jason_etag if @__jason_state == :dirty

  post_headers["X-PARENT"] = self.jason_parent.jason_key if self.jason_parent
  post_headers["X-LIST"] = self.jason_parent_list if self.jason_parent_list

  if opts[:located]
    #set the location headers
    if geohash?
      post_headers["X-GEOHASH"] = geohash
    end
    if latitude? && longitude?
      post_headers["X-LATITUDE"] = latitude
      post_headers["X-LONGITUDE"] = longitude
    end
  end

  post_headers.merge! permissions_header

  url = to_url()

  #puts "Saving to #{url}"
  if method == :post
    response = RestClient.post(url, payload, post_headers)
  elsif method == :delete
    response = RestClient.delete(url, post_headers)
  else
    raise "Unknown method '#{method.to_s}'"
  end

  if response.code == 201
    #save successful!
    #store the new eTag for this object
    #puts response.raw_headers
    @__jason_etag = response.headers[:Etag]
    @__jason_timestamp = response.headers[:timestamp]
  else
    raise "#{method.to_s.upcase} failed! Could not persist changes"
  end

  @__jason_state = :stale
end